reading from file, prints twice

If the text document is like this
"Gone baby Gone"
It prints out the same sentence twice
But if multiple lines are present like
"hello world"
"the world is just awesome"
in text file, then it works fine.
Why does that happen?

1
2
3
4
5
6
7
8
9
      FILE *pFile;
    char mystring[80];
    pFile = fopen("des.txt","r");
    while(!feof(pFile))
    {
        fgets(mystring,80,pFile);
        puts(mystring);
    }
    fclose(pFile);
There's a logic error.

When the fgets reads the last line from the file, that won't necessarily set the eof flag. So the loop executes again, this time fgets finds there is nothing more to be read, eof is set, and the same string mystring is printed again.

Solution. Don't test eof in a while loop condition.

Instead, put the input operation as the condition of the while loop. That way the body of the loop will be executed only when the input succeeded.
1
2
3
4
    while ( fgets(mystring,80,pFile) )
    {
        puts(mystring);
    }





Topic archived. No new replies allowed.