Final Line of a Text File is Printed Twice

1727 views c
3

Assume FILE_NAME is a global constant,

If I have the following code

FILE *file;
file = fopen(FILE_NAME, "r");
char string[30];
do
{
    fgets(string, 30, file);
    printf("%s", string);
}
while ( !feof(file) );

It prints all the lines in the txt file but the last one is printed twice. How do I prevent it from printing twice?

answered question

1 Answer

2

You need to change your loop to:

while ( fgets(string, 30, file) != NULL ) {
    printf("%s", string);
}

fgets() will fail and return NULL before feof(file) becomes true, and it won't update string. So right now you're successfully calling fgets() on the last line, printing it, unsuccessfully calling fgets(), printing the last line again, then terminating your loop.

The key thing to understand here is that you only know you're at the end of the file when you've tried to read from it and your read has failed. Until then, someone might have appended data to the end of the file since the last time you read it, for all you know, for example.

posted this

Have an answer?

JD

Please login first before posting an answer.