A related question is here, but my question is different.
But, I’d like to know more about the internals of getchar() and stdin. I know that getchar() just ultimately calls fgetc(stdin).
My question is about buffering, stdin and getchar() behavior. Given the classic K&R example:
#include <stdio.h>
main()
{
int c;
c = getchar();
while (c != EOF) {
putchar(c);
c = getchar();
}
}
It seems to me that getchar()’s behavior could be described as follows:
If there’s nothing in the stdin buffer, let the OS accept user input until [enter] is pressed. Then return the first character in the buffer.
Assume the program is run and the user types “anchovies.”
So, in the above code listing, the first call to getchar() awaits user input and assigns the first character in the buffer to variable c. Inside the loop, the first iteration’s call to getchar() says “Hey, there’s stuff in the buffer, return the next character in the buffer.” But the Nth iteration of the while loop results in getchar() saying “Hey, there’s nothing in the buffer, so let stdin gather what the user types.
I’ve spend a little time with the c source, but it seems this is more of a behavioral artifact of stdin rather than fgetc().
Am I wrong here? Thanks for your insight.
Not necessarily.
getcharandgetcmight as well expand to the actual procedure of reading from a file, withfgetcimplemented asI can only tell you what I know, and that is how Unix/Linux works. On that platform, a
FILE(including the thing thatstdinpoints to) holds a file descriptor (anint) that is passed to the OS to indicate from which input source theFILEgets data, plus a buffer and some other bookkeeping stuff.The “gather” part then means “call the
readsystem call on the file descriptor to fill the buffer again”. This varies per implementation of C, though.