基于流的I/O--流与缓冲

原文:点击打开链接

基于流的操作最终都会调用read或write进行操作。即流的内部封装了这两个系统调用。

缓冲分如下三种:

全缓冲(相应宏_IO_FULL_BUF):直到缓冲区被填满,菜调用系统I/O函数。磁盘文件读写通常是全缓冲的。

行缓冲(相应宏_IO_LINE_BUF):直到遇到换行符'/n',才调用系统I/O函数。标准输入输出都是行缓冲的。

无缓冲(相应宏_IO_UNBUFFERED):没有缓冲,数据立即读入或输出到外存文件和设备上。例如标准出错。相应宏_IO_UNBUFFERED

检测程序(stdio_buf.c):

#include <stdio.h>

int main()
{  
    // View the infomation of stdin  
    if(stdin->_flags & _IO_UNBUFFERED){
        printf("stdin is unbuffered\n");
    }else if(stdin->_flags & _IO_LINE_BUF){
        printf("stdin is line-buffered\n");
    }else{
        printf("stdin is fully-buffered\n");
    }

    printf("buffer size is %d\n", stdin->_IO_buf_end - stdin->_IO_buf_base);
    printf("discriptor is %d\n\n", fileno(stdin));
   
    // View the infomation of stdin  
    if(stdout->_flags & _IO_UNBUFFERED){
        printf("stdout is unbuffered\n");
    }else if(stdout->_flags & _IO_LINE_BUF){
        printf("stdout is line-buffered\n");
    }else{
        printf("stdout is fully-buffered\n");
    }

    printf("buffer size is %d\n", stdout->_IO_buf_end - stdout->_IO_buf_base);
    printf("discriptor is %d\n\n", fileno(stdout));
   
    // View the infomation of stdin  
    if(stderr->_flags & _IO_UNBUFFERED){
        printf("stderr is unbuffered\n");
    }else if(stderr->_flags & _IO_LINE_BUF){
        printf("stderr is line-buffered\n");
    }else{
        printf("stderr is fully-buffered\n");
    }

    printf("buffer size is %d\n", stderr->_IO_buf_end - stderr->_IO_buf_base);
    printf("discriptor is %d\n\n", fileno(stderr));

    return 0;
}

输出结果:

m@ubuntu ~/W/C> gcc -o stdio_buf stdio_buf.c
m@ubuntu ~/W/C> ./stdio_buf
stdin is fully-buffered
buffer size is 0
discriptor is 0

stdout is line-buffered
buffer size is 1024
discriptor is 1

stderr is unbuffered
buffer size is 0
discriptor is 2

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值