您的位置:首页 > 运维架构 > Linux

【Linux系统编程】IO标准缓冲区

2020-03-06 10:48 260 查看

00. 目录

文章目录

01. 缓冲区概述

标准I/O提供了三种类型的缓冲:

1、全缓冲

在填满标准I/O缓冲区后才进行实际I/O操作。常规文件(如普通文本文件)通常是全缓冲的。

2、行缓冲

当在输入和输出中遇到换行符时,标准I/O库执行I/O操作。这允许我们一次输出一个字符,但只有在写了一行之后才进行实际I/O操作。标准输入和标准输出对应终端设备(如屏幕)时通常是行缓冲的。

3、不带缓冲

用户程序每次调库函数做写操作都要通过系统调用写回内核(如系统调用函数)。标准错误输出通常是无缓冲的,这样用户程序产生的错误信息可以尽快输出到设备。

02. 全缓冲

测试代码:

int main(int argc, char *argv[])
{
FILE *fp = NULL;
// 读写方式打开,文件不存在则创建
fp = fopen("test.txt", "w+");
if(NULL == fp)
{
printf("open error\n");
return 1;
}
char *str = "C++程序员\n";
fwrite(str, 1, strlen(str), fp);	// 往文件写内容
while(1);	// 程序阻塞在这里

return 0;
}

运行程序发现,test.txt并没有内容。因为常规文件通常是全缓冲的,只有缓冲区满了后,才会把内容写到文件中。接下来,我们改一下上面那个例子。

测试代码:

#include <stdio.h>
#include <string.h>

int main(int argc, char *argv[])
{
FILE *fp = NULL;
// 读写方式打开,文件不存在则创建
fp = fopen("test.txt", "w+");
if(NULL == fp)
{
printf("open error\n");
return 1;
}
char *str = "test\n";
int i = 0;
while(i <= 512){	// 缓冲区大小不确定,i的大小只是一个调试值
fwrite(str, 1, strlen(str), fp);	// 往文件写内容
i++;
}
while(1);	// 程序阻塞在这里

return 0;
}

上面的例子是循环给文件写内容,让缓冲区有填满的可能,结果发现,文件是有内容的。实际上要想成功给文件写进内容,除了缓冲区填满,还有别的方法。

2.1 人为关闭文件,就算缓冲区没有填满,内容也会写进文件

#include <stdio.h>
#include <string.h>

int main(int argc, char *argv[])
{
FILE *fp = NULL;
// 读写方式打开,文件不存在则创建
fp = fopen("test.txt", "w+");
if(NULL == fp)
{
printf("open error\n");
return 1;
}
char *str = "test ok\n";
fwrite(str, 1, strlen(str), fp);	// 往文件写内容
fclose(fp);		// 人为关闭文件,就算缓冲区没有填满,内容也会写进文件

while(1);	// 程序阻塞在这里

return 0;
}

2.2 程序正常结束,就算缓冲区没有填满,没有关闭文件,内容也会写进文件。

#include <stdio.h>
#include <string.h>

int main(int argc, char *argv[])
{
FILE *fp = NULL;
// 读写方式打开,文件不存在则创建
fp = fopen("test.txt", "w+");
if(NULL == fp)
{
printf("open error\n");
return 1;
}
char *str = "test ok\n";
fwrite(str, 1, strlen(str), fp);	// 往文件写内容

return 0;
// 程序正常结束,就算缓冲区没有填满,没有关闭文件,内容也会写进文件。
}

03. 行缓冲

#include <stdio.h>

int main(int argc, char *argv[])
{
printf("hello test");
while(1);

return 0;
}

运行这个程序,会发现 hello test并没有打印到屏幕上。因为标准输入和标准输出对应终端设备时通常是行缓冲的,当在输入和输出中遇到换行符时,标准I/O库执行I/O操作。如下:

#include <stdio.h>

int main(int argc, char *argv[])
{
printf("hello test\n");
while(1);

return 0;
}

除了遇到换行符,还有别的方法可以执行I/O操作。

3.1 缓冲区满

int main(int argc, char *argv[])
{
while(1)
{
// 循环打印,总有缓冲区填满的可能
printf("hello sunplusedu");
}
while(1);

return 0;
}

3.2 人为刷新缓冲区

#include <stdio.h>

int main(int argc, char *argv[])
{
printf("hello test");
fflush(stdout);	// 人为刷新

while(1);

return 0;
}

3.3 程序正常结束

#include <stdio.h>

int main(int argc, char *argv[])
{
printf("hello sunplusedu");

return 0;
// 程序正常结束
}

04. 不带缓冲区

#include <unistd.h>
#include <string.h>

int main(int argc, char *argv[])
{
char *str = "hello test";
// 有没有\n,缓冲区有没有填满,都没关系
write(1, str, strlen(str));	// 往标准输出写内容
while(1);

return 0;
}

Linux系统调用中的IO函数一般不带有缓冲区。

05. 附录

  • 点赞 1
  • 收藏
  • 分享
  • 文章举报
沧海一笑-dj 博客专家 发布了641 篇原创文章 · 获赞 2566 · 访问量 91万+ 他的留言板 关注
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: