Linux 标准IO库 全缓冲、行缓冲、无缓冲

1 篇文章 0 订阅
1 篇文章 0 订阅
标准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!”,此时即不可能将缓冲区填满,也没有输出换行符,说明标准错误流是无缓冲的。
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值