0
#include <stdio.h>

int main()
{
    FILE * fp = fopen("Introduce.txt","rt");

    fseek(fp,0,SEEK_END);
    int i = feof(fp);
    printf("%d",i);

    fseek(fp,1,SEEK_END);
    i = feof(fp);
    printf("%d",i);

    fseek(fp,-1,SEEK_END);
    i = feof(fp);
    printf("%d",i);

    return 0;
}

I tried to access EOF positioning 'file position indicator' at the end of the file.
But the result of this code is "000". Why does this happen?

Mr.C64
  • 41,637
  • 14
  • 86
  • 162
Bback.Jone
  • 61
  • 5

2 Answers2

3

The feof() function doesn't report that it is at EOF until you try to read some data and there is no data to read.

You can seek beyond the current EOF of a file that's open for writing (or that's open for reading and writing).

See while (!feof(file)) is always wrong for more information on why you seldom if ever need to use feof(). In some ways, feof() is a function you should forget about — most of your programs will improve if you assume it doesn't exist.

Community
  • 1
  • 1
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
2

This documentation on feof is very clear (emphasis mine):

This function only reports the stream state as reported by the most recent I/O operation, it does not examine the associated data source. For example, if the most recent I/O was a fgetc, which returned the last byte of a file, feof returns zero. The next fgetc fails and changes the stream state to end-of-file. Only then feof returns non-zero.

In typical usage, input stream processing stops on any error; feof and ferror are then used to distinguish between different error conditions.

Mr.C64
  • 41,637
  • 14
  • 86
  • 162