Skip to content


Terminal buffer and getchar(), also side note on EOF

Ever tried this code in a terminal or windows commandline

main() {
    int c;
    while ((c=getchar()) != EOF)
        putchar(c);
}

and wondered why the code only return once a [Enter] key is pressed (thus appearing to be reading a line at a time rather than reading a character at a time)?

The reason is quite simple, when getchar() is called the control is passed to system, which then waits for the user input. Terminals have input buffers which buffers the user input until [enter] is pressed (at which time the buffer is given to the program). The program then of course reads a whole line (including the \n at the end). This can be configured by turning the terminal into non-canonical mode.

As a side note on EOF, in Windows, CTRL+z (^z) at the start of a new line is considered EOF (the character not on the start of the line is considered as the standard Substitute char according to the ASCII table), and on Linux CTRL+D at the beginning of a line sends a EOF.

Posted in C/C++. Tagged with , , , .