Search code examples
cfseekfeof

C: strange behavior of feof


I am new to C. I have stumbled upon certain behavior of feof I can't explain. Specifically in the code below I create a file, write one byte of information int it, then close and open it again, read the information (my 1 byte) till EOF is reached, then move the current position of the file pointer by 0 byte (i.e. do not change the current position at all) and suddenly I am not at the EOF any longer. How come?

#include <stdio.h>
#include <stdint.h>
typedef uint8_t BYTE;

int main(void) {
    FILE* f = fopen("myfile.txt","w");
    BYTE b = 0x0000;
    fwrite(&b,1,1,f);
    fclose(f);
    f = fopen("myfile.txt","r");
    while (!feof(f)){
        fread(&b,1,1,f);
    }
    printf("We have reached EOF: %i \n",feof(f));
    fseek(f,0,SEEK_CUR);
    printf("We have reached EOF: %i \n",feof(f));
} 

Output

We have reached EOF: 1 
We have reached EOF: 0 

Solution

  • From the fseek docs:

    The end-of-file internal indicator of the stream is cleared after a successful call to this function, and all effects from previous calls to ungetc on this stream are dropped.