feof reading last line twice

I am using this code to read in some lines:

1
2
3
4
5
while(!feof(fp))
    {
        fscanf(fp,"%s %d %d %c",word,&x,&y,);
        printf("%s %d %d %c\n",word,x,y,);
}


It works perfectly except for the fact that it reads the last line twice. Anyway of stopping this?
Move the checking after reading
1
2
3
4
5
6
7
while(1)
    {
        fscanf(fp,"%s %d %d %c",word,&x,&y,);
        if ( feof(fp) )
            break; // exit from while
        printf("%s %d %d %c\n",word,x,y,);
}
Last edited on
It works for this but weirdly it doesn't print the last line if it something like this:

1
2
3
4
5
6
7
while(1)
    {
        fscanf(fp,"%s %d",word,&x);
        if ( feof(fp) )
            break; // exit from while
        printf("%s %d\n",word,x);
}



Now it works as long as the last thing I read in is a char it prints the last line fine. Any idea why it does this?
@bazzy: what is the different between your code and his code? it looks the same for me...
In Bazzy's example, you read from the file, then exit if you are at the end. In the first example, you read from the file, and even if it failed due to EOF conditions, it tries to print some data out. In the case of a failed read, the variables remain unchanged and you get a duplicate line of output.
Topic archived. No new replies allowed.