In C file positioning, given a file containing "This is Nagpur", what substring is printed after seeking forward and reading with fgets? #include <stdio.h> int main() { FILE fp; char ch, str[7]; fp = fopen("try.c", "r"); / file 'try.c' contains: This is Nagpur / fseek(fp, 9L, SEEK_CUR); / move 9 bytes from the current position (start) / fgets(str, 5, fp); / read up to 4 chars plus '\0' */ puts(str); return 0; }

Difficulty: Medium

Correct Answer: agpu

Explanation:


Introduction / Context:
This problem checks understanding of byte-wise seeking and bounded line input. fseek moves the file position indicator, and fgets reads a limited number of bytes into a buffer, appending a null terminator.


Given Data / Assumptions:

  • File text: "This is Nagpur" (indices: T0 h1 i2 s3 4 i5 s6 7 N8 a9 g10 p11 u12 r13).
  • fseek(fp, 9L, SEEK_CUR) from the start puts the position at index 9 (character 'a').
  • fgets(str, 5, fp) reads at most 4 characters plus a terminator into str.


Concept / Approach:
Starting at index 9 ('a'), reading 4 characters yields 'a', 'g', 'p', 'u'. fgets writes those and appends '\0', so the buffer contains "agpu".


Step-by-Step Solution:
Seek to index 9 → current char = 'a'.Read 4 chars with fgets → 'a', 'g', 'p', 'u'.Buffer becomes "agpu" → puts prints "agpu" plus a newline.


Verification / Alternative check:
Changing the second argument of fgets to 6 would read 5 characters → "agpur".


Why Other Options Are Wrong:
"Nagp" would require starting at 'N' (index 8). "gpur" starts at index 10, not 9. "agpur" reads 5 letters, exceeding the given size.


Common Pitfalls:
Forgetting that fgets counts the terminator in its size and stops after size-1 characters.


Final Answer:
agpu

More Questions from Input / Output

Discussion & Comments

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