为什么有时候写入文件的内容却没有?没什么printf打印在终端的内容看不到?这一切背后有着怎样早为人知的秘密?缓冲
全缓冲
/*来源:公众号【编程珠玑】
博客:https://www.yanbinghu.com
buff.c*/
#include<stdio.h>
#include<unistd.h>
int main(void)
{
/*以可读可写的方式打开*/
FILE *fp = fopen("./test.txt","w+");
if(NULL == fp)
{
perror("open file failed");
return -1;
}
/*写入内容*/
char buf[] = "wechat:shouwangxiansheng\n";
fwrite(buf,sizeof(char),sizeof(buf),fp);
//fflush(fp);
/*sleep一段时间,以便观察*/
sleep(20);
fclose(fp);
return 0;
}
$ gcc -o buff buff.c
$ ./buff
$ cat test.txt
$ cat test.txt
wechat:shouwangxiansheng
行缓冲
/*来源:公众号【编程珠玑】
博客:https://www.yanbinghu.com
lineBuff.c*/
#include<stdio.h>
#include<unistd.h>
int main(void)
{
printf("wechat:shouwangxiansheng");
sleep(10);
return 0;
}
$ gcc -o lineBuff lineBuff.c
$ ./lineBuff
printf("wechat:shouwangxiansheng\n");
不带缓冲
/*来源:公众号【编程珠玑】
博客:https://www.yanbinghu.com
noBuff.c*/
#include<stdio.h>
#include<unistd.h>
int main(void)
{
fprintf(stderr,"wechat:shouwangxiansheng");
sleep(10);
return 0;
}
总结
通常磁盘上的文件是全缓冲区的 标准输入和标准输入通常是行缓冲的 指向终端设备的流通常是行缓冲,而指向文件时,则是全缓冲 为了尽可能显示错误信息,标准错误是不带缓冲的

推荐阅读
(点击标题可跳转阅读)
【编程之美】用C语言实现状态机(实用)
【超详细C语言】带你吃透贪吃蛇游戏之精髓
