Using fscanf() using feof()

Kraken picture Kraken · Mar 30, 2013 · Viewed 19.3k times · Source

Here's my code.

#include<stdio.h>
void main(){
    FILE *fp;
    int a,b;
    fp=fopen("hello.txt","r");
    while(!feof(fp)){
      fscanf(fp,"%d %d",&a,&b);
      printf("%d %d\n",a,b);
    }
}

My hello.txt is

1   2
3   4

My Output is

1   2
3   4
4   4

Why is my last line being printed twice. Has not fp reached EOF?

Also,the tag in stackoverflow says Usually, when it is used, the code using it is wrong. What does it mean?

Thanks.

Answer

Kerrek SB picture Kerrek SB · Mar 30, 2013

You must never perform an input operation without immediately checking its result!

The following should work:

while (fscanf(fp,"%d %d",&a,&b) == 2)
{
    printf("%d %d\n",a,b);
}

This will stop at the first conversion failure or end of the file. Alternatively, you could distinguish between conversion failures (to skip the erroneous line) and end-of-file; see the documentation of fscanf.