Difficulty: Medium
Correct Answer: Infinite loop
Explanation:
Introduction / Context:
This question evaluates understanding of correct end-of-file handling in C. The function fgetc returns an int so it can signal EOF as a negative value (typically -1). Comparing its result to NULL (0) and storing it in a char leads to a logic error.
Given Data / Assumptions:
i
is of type char.
Concept / Approach:
Assigning fgetc's int result to a char truncates it. If char is unsigned on the implementation, EOF becomes 255 (not equal to 0) and the condition != NULL
remains true forever, repeatedly reading EOF and printing undefined characters. Even with signed char, the condition used is still wrong; the correct test is to use an int and compare to EOF.
Step-by-Step Solution:
Use an int: int c;
Read: while ((c = fgetc(ptr)) != EOF) putchar(c);
Given code instead uses char i
and compares to 0 → EOF never terminates the loop.
Verification / Alternative check:
Test with a small file; observe the program does not terminate and keeps calling fgetc returning EOF.
Why Other Options Are Wrong:
It will not stop at a NULL byte because text files rarely contain one, and the comparison is not checking for EOF correctly. The code compiles, so “Error in program” (compile-time) is misleading.
Common Pitfalls:
Using char for fgetc, and comparing against 0 or '\0' rather than EOF.
Final Answer:
Infinite loop
Discussion & Comments