Linux系统编程9标准IO - fflush

学习自李慧琴老师


引子

#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()。

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Ma浩然

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值