函数名: fflush
功 能: 清除读写缓冲区,需要立即把输出缓冲区的数据进行物理写入时
头文件:stdio.h
原型:int fflush(FILE *stream)
其中stream是要冲洗的流
fflush(stdin)刷新标准输入缓冲区,把输入缓冲区里的东西丢弃[非标准],一般用不到。
fflush(stdout)刷新标准输出缓冲区,把输出缓冲区里的东西打印到标准输出设备上
printf("字符串");后面加fflush(stdout);可提高打印效率!
举例:
#include<stdio.h>
#include<unistd.h>
#include<sys/types.h>
int main()
{
int i = 0;
for(i = 0;i < 10;i ++)
{
printf("%d",i);
sleep(1);
}
return 0;
}
运行结果:
[wanghe@localhost ~]$ ./test_fflush.exe
0123456789[wanghe@localhost ~]$
输出是一次性输出十个数字,而不是挨个输出,说明输出函数先把输出内容放在缓冲区。
下面介绍一个有意思的程序,注意输出函数后面不能加'\n':
#include<stdio.h>
#include<unistd.h>
#include<sys/types.h>
int main()
{
pid_t id;
printf("hello");
id = fork();
return 0;
}
运行结果:
[wanghe@localhost ~]$ ./test_fflush.exe
hellohello[wanghe@localhost ~]$
虽然printf函数是在fork前,但还是输出了两次,因为输出的内容是先存在缓冲区里的,没有遇到‘\n’ '\r'是不会刷新缓冲区的,所以fork后两个几乎一样的进程会输出两次,接下来就要通过使用fflush函数来进行刷新。
#include<stdio.h>
#include<unistd.h>
#include<sys/types.h>
int main()
{
pid_t id;
printf("hello");
fflush(stdout);
id = fork();
return 0;
}
运行结果:
[wanghe@localhost ~]$ ./test_fflush.exe
hello[wanghe@localhost ~]$
printf是一个行缓冲函数
printf函数是标准函数,最终会调用到系统调用函数,printf函数会掉用到write系统函数;但是调用write函数需要满足一些条件件。
(1)缓冲区满
(2)遇到\n
(3)调用fflush函数来冲洗缓冲区
(4)scanf读取缓冲区的内容
(5)调用printf函数的进程或线程结束会调用fflush函数