C file I/O with fseek and fgets: if source.txt contains the single line "Be my friend", what does this program print? #include<stdio.h> int main() { FILE *fs; char c[10]; fs = fopen("source.txt", "r"); c[0] = getc(fs); // read 'B' fseek(fs, 0, SEEK_END); // go to end of file fseek(fs, -3L, SEEK_CUR); // back up 3 bytes fgets(c, 5, fs); // read up to 4 chars into c puts(c); return 0; }

Difficulty: Medium

Correct Answer: end

Explanation:


Introduction / Context:
This problem checks your grasp of random file access with fseek and buffered line reads with fgets. You must reason about byte positions within the file containing the single line "Be my friend".



Given Data / Assumptions:

  • File contents (no trailing newline assumed): "Be my friend".
  • Indices (0-based): B(0) e(1) space(2) m(3) y(4) space(5) f(6) r(7) i(8) e(9) n(10) d(11).
  • fgets(c, 5, fs) reads at most 4 bytes and then appends '\0'.


Concept / Approach:
fseek(fs, 0, SEEK_END) places the file position one past the last character (index 12). The next call fseek(fs, -3L, SEEK_CUR) moves the position back three bytes to index 9, which is the letter 'e' of the word "friend". Then fgets reads up to 4 bytes starting there.



Step-by-Step Solution:
Start: after SEEK_END, position = 12.Back up 3 → position = 9 (character 'e').Call fgets(c, 5, fs): can read up to 4 characters: e(9), n(10), d(11), then EOF.c becomes "end" followed by '\0'.puts(c) prints "end" and adds a newline.



Verification / Alternative check:
If the file had a trailing newline, the three characters before EOF would typically still be 'e', 'n', 'd' for this exact string, so the result remains "end".



Why Other Options Are Wrong:
"friend"/"frien" require seeking much earlier than index 9 or using a larger read size. “Error in fseek” is incorrect because seeking from end with a negative offset is valid. “rien” would start at index 8, not 9.



Common Pitfalls:
Off-by-one mistakes at EOF; forgetting that fgets reads at most n-1 characters; assuming getc affects later fseek behavior (it does not here).



Final Answer:
end

Discussion & Comments

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