学习自李慧琴老师
引子
#include<stdio.h>
#include<stdlib.h>
int main(int argc,char *argv[])
{
int i;
printf("Before while()");
while(1);
printf("After while()");
exit(0);
}
mhr@ubuntu:~/work/linux/stdio$
mhr@ubuntu:~/work/linux/stdio$ gcc test.c
mhr@ubuntu:~/work/linux/stdio$ ./a.out
光标..
结果没有打印 Before while()。为什么呢?
标准输出是典型的行缓冲模式,他是通过换行符来刷新缓冲区,或者一行满了就刷新缓冲区,当前printf 在向标准终端输出的时候,字符即没有满一行,也没有遇到换行符,就不会刷新缓冲区,即不会输出。所以我们在用printf 的时候要加上 \n 这样就会刷新缓冲区,打印目标字符串。
#include<stdio.h>
#include<stdlib.h>
int main(int argc,char *argv[])
{
int i;
printf("Before while()\n");
while(1);
printf("After while()\n");
exit(0);
}
mhr@ubuntu:~/work/linux/stdio$
mhr@ubuntu:~/work/linux/stdio$ gcc test.c
mhr@ubuntu:~/work/linux/stdio$ ./a.out
Before while()
fflush
NAME
fflush - flush a stream 刷新一个流
SYNOPSIS
#include <stdio.h>
int fflush(FILE *stream);
If the stream argument is NULL, fflush() flushes all open output streams.
如果传进的参数为空,fflush 将会刷新所有的打开了输出的流。
也就是当我们有多个流需要同时刷新,我们不用逐个写 fflush(fp) ,直接fflush(NULL)即可。
#include<stdio.h>
#include<stdlib.h>
int main(int argc,char *argv[])
{
int i;
printf("Before while()");
fflush(NULL);
while(1);
printf("After while()");
exit(0);
}
mhr@ubuntu:~/work/linux/stdio$ ./a.out
Before while()
关于缓冲区
缓冲区这个东西存在的最大的作用是 合并系统调用
行缓冲:换行的时候刷新,满了的时候刷新,强制刷新(fflush), 标准输出就是行缓冲
全缓冲:满了的时候刷新,强制刷新,默认都是全缓冲,除了终端设备之外,标准输出是终端设备,所以标准输出是行缓冲
无缓冲: stderr, 出错马上输出,不需要条件。需要立即输出的内容。
缓冲区可以改:setvbuf()。
234

被折叠的 条评论
为什么被折叠?



