In C file I/O, what does this program print from a file until EOF, and what happens in the final printf call? #include <stdio.h> #include <stdlib.h> int main() { FILE fp; unsigned char ch; / file 'abc.c' contains: "This is CuriousTab " / fp = fopen("abc.c", "r"); if (fp == NULL) { printf("Unable to open file"); exit(1); } while ((ch = getc(fp)) != EOF) printf("%c", ch); fclose(fp); printf(" ", ch); / prints just a newline; extra argument is ignored */ return 0; }

Difficulty: Easy

Correct Answer: This is CuriousTab

Explanation:


Introduction / Context:
This question focuses on correct EOF-controlled reading and format-string behavior in printf. The loop prints each character from the file until EOF; the final printf prints a newline regardless of the unused extra argument.


Given Data / Assumptions:

  • File text is "This is CuriousTab ".
  • getc returns the next byte as an int and EOF when the end is reached.
  • Variable ch is unsigned char but the comparison using getc's return value is still valid because the assignment happens before the comparison.


Concept / Approach:
In while ((ch = getc(fp)) != EOF), getc returns an int. The assignment to ch then converts the lower 8 bits, but the comparison uses the promoted int from the assignment expression, which holds the original getc result. As long as the character read is not EOF, the body prints it. After the loop, fclose closes the stream. The final printf("\n", ch) ignores the superfluous argument and prints only a newline.


Step-by-Step Solution:
Read and echo characters → outputs "This is CuriousTab " including the trailing space.Close file → emit a newline.Net visible line → "This is CuriousTab" (trailing space not visible at the end in the option wording).


Verification / Alternative check:
Replace getc with fgetc and store into an int to avoid any subtlety with unsigned char; output is the same.


Why Other Options Are Wrong:
It is not an infinite loop and there is no error. Truncating at "This is" would require an early stop condition that does not exist here.


Common Pitfalls:
Misusing printf format strings (unused arguments are ignored) and misunderstanding the role of EOF and int return types for character input.


Final Answer:
This is CuriousTab

Discussion & Comments

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