#include <stdio.h>
int main(){
int c;
while((c = getchar()) != EOF)){
putchar(c);
}
}
This is the code from R&K's first charpter. I am confused by the behavior of putchar(): why doesn't putchar() output my input until I press enter?
It seems to me that the while loop is continuous reading my input and print characters, but the output doesn't reveal itself untile I press enter.
Can anyone explain the mechanism behind it?
Input and output are buffered, meaning most characters are not immediately transmitted. For efficiency (and some user interface considerations), multiple characters are kept into a buffer for a period of time and later transmitted as a group.
Most commonly, when a simple C program is reading from a terminal, the terminal software interprets key presses, translates some of them to characters (like the keyboard K key to the character “K” or the Enter key to the new-line character1). For many of these characters, it does not immediately send them to the program. It accumulates characters until you press Enter or Return and then sends the characters to the program. (It may will also send accumulated characters when there are so many that its buffer is full or when some special events happen.)
Inside your program, when it first executes getchar
, the program asks the operating system for data from the input device. However, the terminal has not sent anything yet, so the operating system blocks your program2. Eventually, you press Enter or Return, and the terminal software sends the accumulated characters to your program. Then the operating system puts the data inside your program’s buffer and unblocks your program.
Then the getchar
routine takes one character from the buffer and returns its value.
Then your program passes that character value to putchar
. putchar
puts the character in another buffer inside your program.
The loop continues to execute, with getchar
getting characters from the input buffer and putchar
putting them into the output buffer.
Eventually, your program sends the new-line character to putchar
. Then putchar
sends all the characters in the buffer to the operating system, to be sent to the output device. When that device is terminal software, the terminal software displays the characters on your display.
1 Not every key press becomes a character. Some keys become characters when combined with other keys, like Shift-H together to make “H” instead of “h” or Option-E followed by A to make “á”. Some act as interruptions, commands, or other special events instead of being translated to characters, such as Control-C to interrupt a program.
2 Your program runs in a process that can have multiple threads, but I will not get into details about that in this answer.