标准IO库提供缓冲的目的是尽可能减少使用read、write系统调用的次数。
标准IO提供以下三种缓冲机制:
1. 全缓冲:在填满标准IO缓冲区后才进行实际IO操作,对于磁盘文件的IO通常是由标准IO库实施全缓冲的。
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
int main(int argc,char * argv[])
{
FILE * fp;
char buff[20];
if((fp = fopen("test.txt","a"))==NULL){
perror("fopen");
exit(-1);
}
strcpy(buff,"this is a test!\n");
fwrite(buff,strlen(buff),1,fp);
printf("sleeping\n");
sleep(10);
printf("wakeup!\n");
fclose(fp);
exit(0);
}
编译并运行程序,当输出:sleeping 以后查看test.txt里面并没有内容,等输出:wakeup 后再查看文件,“”this is a test!“”已经在里面了,说明文件IO默认是全缓冲的,如果缓冲区未填满,当进程退出或者关闭文件时才会进行真正的IO操作。
2. 行缓冲 :当流涉及一个终端时(如标准输入输出)通常使用行缓冲。
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
int main(int argc,char * argv[])
{
fprintf(stdout,"this is a test!","%s");
sleep(5);
printf("print a \\n!\n");
sleep(5);
exit(0);
}
编译并运行程序,在输出‘\n’符之前,终端并没有输出。五秒过后终端输出“this is a test!print a \n!”。
3. 无缓冲:标准错误流stderr通常是不带缓冲的,这能够使错误尽快的显示出来。
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
int main(int argc,char * argv[])
{
fprintf(stderr,"this is a test!","%s");
sleep(5);
exit(0);
}
编译并运行程序:程序一运行就会输出“this is s test!”,此时即不可能将缓冲区填满,也没有输出换行符,说明标准错误流是无缓冲的。