在写代码中,我们会经常换行,让输出的结果看起来更有条理,更易观察。
先上源代码,这是一个select的小demo,按一次键就将键值输出。
#include #include #include #include #include #include int main(){ fd_set readfd; int keyboard = open("/dev/tty",O_RDONLY|O_NONBLOCK); char c; struct timeval timeout; while(1){ timeout.tv_sec = 1; timeout.tv_usec = 0; FD_ZERO(&readfd); FD_SET(keyboard,&readfd); int ret = select(keyboard+1,&readfd,NULL,NULL,&timeout); if(FD_ISSET(keyboard,&readfd)){ int i = read(keyboard,&c,1); if(c == '\n'){ continue; } printf("The input is: %c",c); if(c == 'q') break; } } return 0;}
1.在第23行printf("The input is: %c",c);处没有换行,运行代码的结果如下:
很明显,在程序运行之间,输出缓冲区的内容没有打印出来,程序退出时才打印出来
2.在第23行printf("The input is: %c",c);有换行 ,运行结果如下图:
结果是按照自己的逻辑输出的
原因,printf的缓冲是行缓冲,意思就是当行缓冲里被填满的时候就把缓冲里的内容打印输出,所以当没有'\n'的时候,缓冲没有满,输出就是上面截图所示,当有'\n'的时候,就相当于缓冲满了,会打印输出。