1. Home
  2. Computer Science MCQs
  3. C Programming
  4. Why does the loop while (!feof(fp)) { fgets(line, n, fp)…

Added 30 Nov -0001

Why does the loop while (!feof(fp)) { fgets(line, n, fp); puts(line); } often print the last line twice?

  1. fgets rewinds the file when it reaches the last record, so the final line is read again
  2. feof returns true at the start of the last line, so the guard terminates far too early
  3. puts flushes the buffer twice when the final newline is missing from the file
  4. feof only becomes true after a read hits end of file, so one extra iteration runs Correct answer

Correct answer

D. feof only becomes true after a read hits end of file, so one extra iteration runs

14 views

MCQSEXAM

Explanation

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.

Reference

Asked in: NTS, PPSC IT, Campus Interviews

Preparing for an exam?

Doubts & discussion

Not sure why the answer is D? Ask here and get an explanation.

Ask a doubt about this MCQ

Shown after review. No links please.

More C Programming MCQs

Practise all C Programming MCQs

Similar MCQs