In C file I/O, what happens when fgetc() is compared to NULL and the character variable is of type char? #include <stdio.h> int main() { FILE *ptr; char i; ptr = fopen("myfile.c", "r"); while ((i = fgetc(ptr)) != NULL) printf("%c", i); return 0; }

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.
  • Loop condition compares result to NULL (0) rather than EOF (-1).
  • At EOF, fgetc returns EOF each time it is called.

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

More Questions from Input / Output

Discussion & Comments

No comments yet. Be the first to comment!
Join Discussion