转自:http://blog.csdn.net/tennysonsky/article/details/43490985
标准I/O库提供缓冲的目的是尽可能地减少使用read和write调用的次数。它也对每个I/O流自动地进行缓冲管理,从而避免了应用程序需要考虑这一点所带来的麻烦。不幸的是,标准I/O库最令人迷惑的也是它的缓冲。
标准I/O提供了三种类型的缓冲:
1、全缓冲:
在填满标准I/O缓冲区后才进行实际I/O操作。常规文件(如普通文本文件)通常是全缓冲的。
2、行缓冲:
当在输入和输出中遇到换行符时,标准I/O库执行I/O操作。这允许我们一次输出一个字符,但只有在写了一行之后才进行实际I/O操作。标准输入和标准输出对应终端设备(如屏幕)时通常是行缓冲的。
3、不带缓冲:
用户程序每次调库函数做写操作都要通过系统调用写回内核(如系统调用函数)。标准错误输出通常是无缓冲的,这样用户程序产生的错误信息可以尽快输出到设备。
下面是各个缓冲区的验证。
全缓冲:
-
int main(int argc, char *argv[])
-
{
-
FILE *fp = NULL;
-
-
fp = fopen("sunplusedu.txt", "w+");
-
if(NULL == fp)
-
{
-
printf("open error\n");
-
return 1;
-
}
-
char *str = "sunplusedu\n";
-
fwrite(str, 1, strlen(str), fp);
-
while(1);
-
-
return 0;
-
}
运行程序发现,sunplusedu.txt并没有内容。因为常规文件通常是全缓冲的,只有缓冲区满了后,才会把内容写到文件中。接下来,我们改一下上面那个例子。
-
#include <stdio.h>
-
#include <string.h>
-
-
int main(int argc, char *argv[])
-
{
-
FILE *fp = NULL;
-
-
fp = fopen("sunplusedu.txt", "w+");
-
if(NULL == fp)
-
{
-
printf("open error\n");
-
return 1;
-
}
-
char *str = "sunplusedu\n";
-
int i = 0;
-
while(i <= 512){
-
fwrite(str, 1, strlen(str), fp);
-
i++;
-
}
-
while(1);
-
-
return 0;
-
}
上面的例子是循环给文件写内容,让缓冲区有填满的可能,结果发现,文件是有内容的。实际上要想成功给文件写进内容,除了缓冲区填满,还有别的方法。
1)人为关闭文件,就算缓冲区没有填满,内容也会写进文件
-
#include <stdio.h>
-
#include <string.h>
-
-
int main(int argc, char *argv[])
-
{
-
FILE *fp = NULL;
-
-
fp = fopen("sunplusedu.txt", "w+");
-
if(NULL == fp)
-
{
-
printf("open error\n");
-
return 1;
-
}
-
char *str = "sunplusedu\n";
-
fwrite(str, 1, strlen(str), fp);
-
fclose(fp);
-
-
while(1);
-
-
return 0;
-
}
2)程序正常结束,就算缓冲区没有填满,没有关闭文件,内容也会写进文件。
-
#include <stdio.h>
-
#include <string.h>
-
-
int main(int argc, char *argv[])
-
{
-
FILE *fp = NULL;
-
-
fp = fopen("sunplusedu.txt", "w+");
-
if(NULL == fp)
-
{
-
printf("open error\n");
-
return 1;
-
}
-
char *str = "sunplusedu\n";
-
fwrite(str, 1, strlen(str), fp);
-
-
return 0;
-
-
}
行缓冲:
-
#include <stdio.h>
-
-
int main(int argc, char *argv[])
-
{
-
printf("hello sunplusedu");
-
while(1);
-
-
return 0;
-
}
运行这个程序,会发现 hello sunplusedu 并没有打印到屏幕上。因为标准输入和标准输出对应终端设备时通常是行缓冲的,当在输入和输出中遇到换行符时,标准I/O库执行I/O操作。如下:
-
#include <stdio.h>
-
-
int main(int argc, char *argv[])
-
{
-
printf("hello sunplusedu\n");
-
while(1);
-
-
return 0;
-
}
除了遇到换行符,还有别的方法可以执行I/O操作。
1)缓冲区填满
-
int main(int argc, char *argv[])
-
{
-
while(1){
-
printf("hello sunplusedu");
-
}
-
while(1);
-
-
return 0;
-
}
2)人为刷新缓冲区
-
#include <stdio.h>
-
-
int main(int argc, char *argv[])
-
{
-
printf("hello sunplusedu");
-
fflush(stdout);
-
-
while(1);
-
-
return 0;
-
}
3)程序正常结束
-
#include <stdio.h>
-
-
int main(int argc, char *argv[])
-
{
-
printf("hello sunplusedu");
-
-
return 0;
-
-
}
不带缓冲:
-
#include <unistd.h>
-
#include <string.h>
-
-
int main(int argc, char *argv[])
-
{
-
char *str = "hello sunplusedu.com";
-
-
write(1, str, strlen(str));
-
while(1);
-
-
return 0;
-
}
浅谈标准I/O缓冲区
原文:http://blog.csdn.net/lianghe_work/article/details/46602423