-
Problem with a loop
When I put the following code in a loop it will not write to the file. When I take it out of the loop it works fine (I realize that for now it is an infinite loop as that is part of the assignment). Any suggestions?
Code:
while(!done) {
printf("Enter line #%d: ",line_count++);
if (fgets(user_line,MAX_LINE_LENGTH,stdin) == NULL) {
fprintf(stderr,"Error reading user input: %s\n", strerror(errno));
}
if (fputs(user_line,memo_pntr) == EOF) {
fprintf(stderr,"Error writing to file %s: %s\n",memo_file_path, strerror(errno));
}
}
Thanks!
-
Did you check stderr for errors?
Do you close the file (fclose()) after this loop? Maybe because the file is terminated violently (since it has infinite loop) the buffer isn't written to the file? Just a wild guess...
-
Are you sure that you're entering the loop? To enter that loop the value of done must be zero. Post a short example that both compiles and demonstrates the problem - without seeing how you've set up the variables you're using it's hard to see what you're doing wrong.
-
Yeah, I'm entering the loop and it closes afterwards (although with the current design it will never hit the close). I want to force the user to use cntrl-c to end for now.
Here is the whole code:
Code:
/*
*CS306 Lab 5 lab5.c
*Author: Chris Wiegman
*Execute the memo program as specified in lab 5.
*
*Call as:
* memo [MEMO_FILE]
*/
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#define WAIT_TIME 10
#define MAX_LINE_LENGTH 100
void sigalrm_handler(int signal);
void sigint_handler(int signal);
void sigquit_handler(int signal);
void error_cleanup();
char *memo_file_path = NULL;
FILE *memo_pntr;
int main(int argc, char *argv[]) {
int line_count = 1, done = 0;
char user_line[MAX_LINE_LENGTH+1];
switch (argc) {
case 1:
memo_file_path = "memo.text";
break;
case 2:
memo_file_path = argv[1];
break;
default:
fprintf(stderr,"Usage: memo [MEMO_FILE]\n");
return EXIT_FAILURE;
break;
}
if ((memo_pntr = fopen(memo_file_path, "w+")) == NULL) {
fprintf(stderr,"Error opening file %s: %s\n",memo_file_path, strerror(errno));
return EXIT_FAILURE;
}
while(!done) {
printf("Enter line #%d: ",line_count++);
if (fgets(user_line,MAX_LINE_LENGTH,stdin) == NULL) {
fprintf(stderr,"Error reading user input: %s\n", strerror(errno));
}
if (fputs(user_line,memo_pntr) == EOF) {
fprintf(stderr,"Error writing to file %s: %s\n",memo_file_path, strerror(errno));
}
}
fclose(memo_pntr);
return EXIT_SUCCESS;
}
void sigalrm_handler(int signal) {
}
void sigint_handler(int signal) {
}
void sigquit_handler(int signal) {
}
void error_cleanup() {
}
-
Add fflush(memo_pntr) after you use fputs, or replace fputs with an fprintf. fputs must not flush the output buffer on completion.
[edit]
This explains the behaviour - and I'll guess that without the loop you were closing the file afterwards.
http://crasseux.com/books/ctutorial/fputs.html
[/edit]
-