Theory Behind getchar() and putchar() Functions

Rae*_*ven 6 c putchar getchar

I'm working through "The C Programming Language" by K&R and example 1.5 has stumped me:

#include <stdio.h>

/* copy input to output; 1st version */
int main(int argc, char *argv[])
{
    int c;

    while ((c = getchar()) != EOF)
        putchar(c);

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

I understand that 'getchar()' takes a character for 'putchar()' to display. However, when I run the program in terminal, why is it that I can pass an entire line of characters for 'putchar()' to display?

Kni*_*nug 20

因为您的终端是行缓冲的.getchar()并且putchar()仍然只处理单个字符,但终端等待提交字符到程序,直到您输入整行.然后getchar()逐个从缓冲区中获取字符并逐个putchar()显示它们.

另外:终端是行缓冲的意思是它在遇到换行符时向程序提交输入.提交数据块通常更有效,而不是一次提交一个字符.它还为用户提供了在按Enter之前编辑线的机会.

注意:可以通过禁用终端的规范模式并使用on 调用setbuf来关闭线路缓冲.NULLstdin