Why does the loop while (!feof(fp)) { fgets(line, n, fp); puts(line); } often print the last line twice?
Correct answer
D. feof only becomes true after a read hits end of file, so one extra iteration runs
14 views
D. feof only becomes true after a read hits end of file, so one extra iteration runs
14 views
feof reports a sticky flag set only after a read attempts to pass the end, so testing it before the read lets one failed fgets process a stale buffer. The robust pattern tests the return value instead: while (fgets(line, n, fp)) { ... }. The same misuse with fscanf duplicates the final record, a common trap in file-handling questions.
Asked in: NTS, PPSC IT, Campus Interviews
Not sure why the answer is D? Ask here and get an explanation.