小甲鱼 P61 IO缓冲区
小甲鱼 P61 IO缓冲区
IO缓冲区
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
FILE *fp;
if ((fp = fopen("output.txt", "w")) == NULL)
{
perror("打开文件失败,原因是");
exit(EXIT_FAILURE);
}
fputs("I love FishC.com!\n", fp);
//阻塞函数,只有函数完成调用返回,程序才会结束
getchar();
fclose(fp);
return 0;
}
fflush()函数:刷新缓冲区,将缓冲区里面的数据立刻存放到目标位置中。希望不使用IO缓冲区,希望数据立刻写入到设备
标准IO提供的三种类型的缓冲模式:
按块缓存 _IOFBF
按行缓存 _IOLBF
不缓存 _IONBF
setvbuf()函数:
#include <stdio.h>
#include <string.h>
int main(void)
{
char buff[1024];
memset(buff, '\0', sizeof(buff));
setvbuf(stdout, buff, _IOFBF, 1024);//设置按块缓存
fprintf(stdout, "Welcome to hello world\n");
fflush(stdout);//将缓冲区的数据强行写入设备
fprintf(stdout, "输入任意字符后才会显示该行字符!\n");
getchar(); //阻塞,塞进缓冲区
return 0;
}