一、标准 I/O缓存类型
I/O缓冲的目的是使用read和write时尽可能少的访问硬盘次数
标准I/O提供了三种类型的缓冲:
- 全缓存
在填满缓冲区后才进行I/O操作。常规文件(如普通文本文件)通常是全缓冲的 - 行缓存
当在输入和输出中遇到换行符时进行I/O操作。标准输入和标准输出对应终端设备(如屏幕)时通常是行缓冲的 - 不缓存
每次输入和输出操作都进行I/O操作。标准错误输出通常是无缓冲的,这样用户程序产生的错误信息可以尽快输出到设备
二、全缓存 - 普通文件
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char *argv[])
{
FILE *fp = fopen("test_io.txt", "w+");
const char *str = "hello world\n";
/* 缓冲区不满,文件中没有内容
fwrite(str, 1, strlen(str), fp);
while(1);
*/
/* 缓冲区满,文件中有内容
for (int i=0; i<512; i++)
{
fwrite(str, 1, strlen(str), fp);
}
while(1);
*/
/* 手动刷新,文件中有内容
fwrite(str, 1, strlen(str), fp);
fflush(fp);
while(1);
*/
/* 手动关闭文件,文件中有内容
fwrite(str, 1, strlen(str), fp);
fclose(fp);
while(1);
*/
/* 程序正常结束,文件中有内容
fwrite(str, 1, strlen(str), fp);
return 0;
*/
return 0;
}
三、行缓存 - 标准输出
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
/* 没有换行符,不打印到屏幕
printf("hello world");
while(1);
*/
/* 有换行符,打印到屏幕
printf("hello world\n");
while(1);
*/
/* 缓冲区满,打印到屏幕
for (int i=0; i<512; i++)
{
printf("hello world");
}
while(1);
*/
/* 手动刷新,打印到屏幕
printf("hello world");
fflush(stdout);
while(1);
*/
/* 程序正常结束,打印到屏幕
printf("hello world");
return 0;
*/
return 0;
}
四、不缓存 - 标准错误输出
#include <unistd.h>
#include <string.h>
int main(int argc, char *argv[])
{
char *str = "hello world";
write(2, str, strlen(str));
while(1);
return 0;
}