A structured lesson workspace with readable content, hands-on examples, and a clean path to completion.
feof does not predict whether the next read will hit end-of-file. It reports whether a previous read already hit end-of-file. This distinction causes the most repeated C file-reading bug: a while (!feof(fp)) loop that processes the last record twice. The flag is not set until a read attempt fails. By then, your loop body has already executed with stale data.
#include <stdio.h>int main(void) {FILE *fp = fopen("numbers.txt", "w");fputs("10\n20\n30\n", fp);fclose(fp);fp = fopen("numbers.txt", "r");int value;int count = 0;while (!feof(fp)) {fscanf(fp, "%d", &value);printf("Read: %d\n", value);count++;}printf("Total reads: %d\n", count);fclose(fp);return 0;}
Four reads for three values. The last value, 30, is printed twice. Here is why: after reading 30, the position is at the newline before EOF. feof is still false because no read has failed yet. The loop enters a fourth time. fscanf fails to match, leaves value unchanged (still 30), and only now does the EOF flag get set. The loop body prints the stale value before the condition is rechecked.
#include <stdio.h>int main(void) {FILE *fp = fopen("numbers.txt", "r");int value;int count = 0;while (fscanf(fp, "%d", &value) == 1) {printf("Read: %d\n", value);count++;}printf("Total reads: %d\n", count);fclose(fp);return 0;}
Check the return value of the read function in the loop condition. fscanf returns the number of items successfully read. When it returns something other than 1, you stop. No feof needed. The same pattern applies to fgets: while (fgets(buf, size, fp) != NULL). The read function tells you whether it succeeded. feof tells you why it failed, after the fact.
This bug appears in Stack Overflow questions, in textbook code, and in production systems. The fix is always the same: put the read call in the loop condition. feof is useful after the loop to distinguish "ended because EOF" from "ended because of a parse error." It is not useful as a loop guard. Next: stderr, the unbuffered diagnostic stream.
Finish the lesson once you have worked through the material. This awards ★ 20 XP.