EOF, feof & Stream Errors in C
Input functions signal trouble through return values plus two sticky stream flags: EOF (-1) marks end-of-file or error on character reads, feof() reports the end flag, and ferror() reports the error flag. The classic bug is while (!feof(fp)) — feof only trips AFTER a failed read, so the loop processes the last item twice; the correct pattern tests the read itself (while (fgets(...) != NULL), while ((c = getchar()) != EOF)).
Clear flags with clearerr() when recovering, and distinguish the two causes: feof means data ran out (normal), ferror means something broke (disk, pipe). Robust readers check returns first and consult flags only to explain failures.
Test the read, not feof
while (fgets(buf, n, fp) != NULL) ends exactly at input end; while (!feof(fp)) overruns by one ghost iteration.
EOF is -1, sticky flags
getchar returns EOF once input ends or errors; feof/ferror then stick until clearerr() resets them.
Explain failures with flags
After a NULL/failed read, feof() vs ferror() tells normal-exhaustion apart from real breakage.
perror narrates errno
perror("read") prints your prefix plus the system's reason (Permission denied, etc.) from errno.
#include <stdio.h> int main(void) { int c; long chars = 0; while ((c = getchar()) != EOF) ++chars; if (ferror(stdin)) fprintf(stderr, "read error\n"); else printf("%ld chars\n", chars); return 0;}Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in C yourself — building beats watching.