Counting reads through shared stream pointers

A C diagnostic program reads an unchanged file containing exactly 40 bytes. Both calls to fopen below succeed. No input errors occur, and both calls to ungetc succeed.


The helper drain(s) repeatedly calls fgetc(s) until it returns EOF. The helper returns the number of calls that returned characters, excluding the final call that returned EOF. It neither closes nor repositions the stream.


C
FILE *a = fopen("capture.bin", "rb");
FILE *again = a;
FILE *b = fopen("capture.bin", "rb");

for (int i = 0; i < 8; ++i)
    (void)fgetc(a);
for (int i = 0; i < 5; ++i)
    (void)fgetc(again);
for (int i = 0; i < 11; ++i)
    (void)fgetc(b);

(void)ungetc('X', again);
unsigned first = drain(a);

(void)ungetc('Y', again);
unsigned second = drain(a);

unsigned third = drain(b);


All 24 calls to fgetc in the three initial loops return characters. Find first, second, and third, each measured in characters returned. Also find the total number of characters returned by fgetc across the initial loops and all three drains. Count repeated delivery of a character each time it occurs, and exclude the return values of ungetc. Give all four answers as exact integers.

Your answers

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

More Streams Questions: