0

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 
zesy
  • 481
  • 5
  • 12
  • https://stackoverflow.com/q/5431941/905902 – wildplasser Dec 26 '17 at 14:32
  • @wildplasser the question you referenced seems to talk about my problem, but the discussion/ answers there are too advanced for me. – zesy Dec 26 '17 at 14:48
  • 2
    Uh, guys? Didn't you jump the gun with that `while(!feof())`? It's perfectly appropriate here... – Quentin Dec 26 '17 at 14:48
  • @Quentin: the question is indeed different, and feof() *could* be usable here. But IMO it is either an overly complex way of doing it, or a learning exercise, in which case the other answers could help. – wildplasser Dec 26 '17 at 14:55

1 Answers1

3

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.

Nick
  • 4,901
  • 40
  • 61