Effect of fseek in a read loop: Given the code that copies from source.txt to target.txt but calls fseek(fs, 4L, SEEK_CUR) after each character read, what will be written to 'target.txt' if the source line is "To err is human"?

Difficulty: Medium

Correct Answer: Trh

Explanation:


Introduction / Context:
This problem tests understanding of file positioning functions in C, specifically how fseek interacts with sequential reading in a loop. By skipping a fixed number of bytes after each successful read, the program samples characters at a specific stride across the source text. Predicting the resulting output requires careful attention to the order of operations and the stride length.


Given Data / Assumptions:

  • Source text is exactly: "To err is human" (including spaces, no trailing newline considered).
  • The loop reads one character at a time using getc(fs).
  • After each non-EOF character, the code executes fseek(fs, 4L, SEEK_CUR) and then writes the character to the output with fputc.
  • Files open in text mode; each seek moves the position in bytes across this ASCII text.


Concept / Approach:

  • Each iteration reads one byte, then skips forward 4 bytes due to fseek with SEEK_CUR.
  • This creates an effective stride of 5 bytes per iteration (1 read + 4 skipped).
  • The resulting output is every 5th character of the source, starting from index 0.


Step-by-Step Solution:

Index characters (0-based): 0:T, 1:o, 2: , 3:e, 4:r, 5:r, 6: , 7:i, 8:s, 9: , 10:h, 11:u, 12:m, 13:a, 14:n.Iteration 1: read index 0 → 'T'; seek +4 → next read index 5.Iteration 2: read index 5 → 'r'; seek +4 → next read index 10.Iteration 3: read index 10 → 'h'; seek +4 → next would be index 15 (past end) → EOF, loop ends.


Verification / Alternative check:

Concatenate captured characters → 'T' + 'r' + 'h' = 'Trh', matching the predicted output.


Why Other Options Are Wrong:

  • 'r n': Misinterprets spacing and skip pattern; does not align with the 5-byte stride.
  • 'err': Would require reading contiguous indices 2–4 or similar, which the code does not do.
  • None of above: Incorrect because 'Trh' is precisely produced by the loop.


Common Pitfalls:

  • Forgetting that the seek occurs after the character is read and queued for write.
  • Assuming fseek skips characters without considering the initial position and EOF handling.


Final Answer:

Trh

More Questions from Input / Output

Discussion & Comments

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