Alex Rivera | Logout

getchar() and stdin

Asked 2011-10-12T14:45:26.200
8

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.

c
Edit
Report

1 Answer

8

getchar()'s input is line-buffered, and the input-buffer is limited, usually it's 4 kB. What you see at first is the echo of each character you're typing. When your press ENTER, then getchar() starts returning characters up to the LF (which is converted to CR-LF). When you keep on pressing keys without LF for some time, it stops echoing after 4096 characters, you have to press ENTER to continue.

answered 2011-10-12T15:31:36.077

Your Answer