How does feof () really know when the end of file is reached?
When the code tries to read the past character.
Depending on the type of file, the last character is necessarily known until an attempt is made to read it and the character is not available.
Code sample showing feof() going from 0 to 1
#include <stdio.h> void ftest(int n) { FILE *ostream = fopen("tmp.txt", "w"); if (ostream) { while (n--) { fputc('x', ostream); } fclose(ostream); } FILE *istream = fopen("tmp.txt", "r"); if (istream) { char buf[10]; printf("feof() %d\n", feof(istream)); printf("fread %zu\n", fread(buf, 1, 10, istream)); printf("feof() %d\n", feof(istream)); printf("fread %zu\n", fread(buf, 1, 10, istream)); printf("feof() %d\n", feof(istream)); puts(""); fclose(istream); } } int main(void) { ftest(9); ftest(10); return 0; }
Exit
feof() 0 fread 9 // 10 character read attempted, 9 were read feof() 1 // eof is set as previous read attempted to read passed the 9th or last char fread 0 feof() 1 feof() 0 fread 10 // 10 character read attempted, 10 were read feof() 0 // eof is still clear as no attempt to read passed the 10th, last char fread 0 feof() 1
chux source share