I wanted to read the following text file which has an extra line at the end (test.txt):
345
<--empty line
I wrote the following C code:
FILE *fp;
char line[80], *myResult;
fp = fopen("test.txt", "rt");
while (!feof(fp))
{
myResult = fgets(line, 80, fp);
printf("line = %s", line);
printf("myResult = %s", myResult);
printf("feof(fp) = %d\n", feof(fp));
}
The output was:
line = 345
myResult = 345
feof(fp) = 0
line = 345
myResult = (null)feof(fp) = 16
I was surprised to see “line = 345” being written twice although there is only one value inside the file. My guess is that when fgets reads the last line, it directly returns NULL and while doing so it does not modify the value that was pointed to by “line”, so “line” stays at the same value from previous step.
I modified the while loop as follows:
while (fgets(line, 80, fp) != NULL) { printf("line = %s", line); }
New output is just one line as expected:
line = 345
Lesson learnt: Don’t use eof() in your while loop, use the return value of fgets() to check end of file.
No comments:
Post a Comment