0

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?

Joshua
  • 19
  • 1
  • 3
  • 1
    [Why is “while ( !feof (file) )” always wrong?](https://stackoverflow.com/questions/5431941/why-is-while-feof-file-always-wrong) – Swordfish Nov 07 '18 at 01:53

1 Answers1

1

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.

Crowman
  • 25,242
  • 5
  • 48
  • 56