In C file handling, two streams open the same file in write mode. After writing a character through each stream, what remains in the file? #include <stdio.h> int main() { FILE *fp1, *fp2; fp1 = fopen("file.c", "w"); fp2 = fopen("file.c", "w"); fputc('A', fp1); fputc('B', fp2); fclose(fp1); fclose(fp2); return 0; }

Difficulty: Easy

Correct Answer: B

Explanation:


Introduction / Context:
This question assesses understanding of fopen modes and how multiple write-mode openings affect file contents. Opening in mode "w" truncates the file immediately, and each stream maintains its own file position.


Given Data / Assumptions:

  • Both fp1 and fp2 open the same path with mode "w".
  • Each stream begins at file position 0 after its own truncation.
  • Writes occur in the order: 'A' via fp1, then 'B' via fp2.


Concept / Approach:
The second fopen("w") truncates the file again. Each subsequent fputc writes at that stream's current position (start). Because the final write is 'B' through fp2, the byte at position 0 becomes 'B'. No other bytes are written.


Step-by-Step Solution:
fp1 opens → file truncated → position 0.fp2 opens → file truncated again → position 0.fputc('A', fp1) writes 'A' at pos 0 in fp1's view.fputc('B', fp2) writes 'B' at pos 0 via fp2, overwriting earlier content.Close both → final file contains exactly 'B'.


Verification / Alternative check:
Reading the file after the program exits yields a single-byte file with ASCII 'B'.


Why Other Options Are Wrong:
"A B" suggests two bytes written, but each stream wrote only once at position 0. "B B" implies two bytes; not the case. The filename in the error option is different and there is no error shown.


Common Pitfalls:
Assuming streams coordinate positions automatically; they do not. Each stream has its own buffer and file position.


Final Answer:
B

More Questions from Input / Output

Discussion & Comments

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