linux I/O缓存类型


一、标准 I/O缓存类型

I/O缓冲的目的是使用read和write时尽可能少的访问硬盘次数
在这里插入图片描述

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

  1. 全缓存
    在填满缓冲区后才进行I/O操作。常规文件(如普通文本文件)通常是全缓冲的
  2. 行缓存
    当在输入和输出中遇到换行符时进行I/O操作。标准输入和标准输出对应终端设备(如屏幕)时通常是行缓冲的
  3. 不缓存
    每次输入和输出操作都进行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;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值