Learn C
#include "ioformatting/eof_errors.h"

EOF, feof & Stream Errors in C

#concept

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.

#how it works
1

Test the read, not feof

while (fgets(buf, n, fp) != NULL) ends exactly at input end; while (!feof(fp)) overruns by one ghost iteration.

2

EOF is -1, sticky flags

getchar returns EOF once input ends or errors; feof/ferror then stick until clearerr() resets them.

3

Explain failures with flags

After a NULL/failed read, feof() vs ferror() tells normal-exhaustion apart from real breakage.

4

perror narrates errno

perror("read") prints your prefix plus the system's reason (Permission denied, etc.) from errno.

#example
#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;
}
Output
10 chars
1The loop consumes input until getchar reports EOF — the read itself is the condition, never feof.
2Afterward, ferror distinguishes a broken stream from clean exhaustion.
3Clean input of 10 characters prints the count; only real errors take the stderr path.
#use cases
Replacing every while (!feof(...)) with read-tested loops
Distinguishing truncated input from I/O failures in tools
perror() messages that explain failures to users
clearerr() recovery when retrying flaky streams

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in C yourself — building beats watching.