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

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

 

缓冲分如下三种:

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

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

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

 

在判断流用的是那种缓冲时,应将文件流对象中的缓冲区标志与该宏“与”操作,判断结果是否为0就行了。

 

 

范例:

//buf.c

#include <stdio.h>

int main(void)
{   
    printf("stdin is ");
    if(stdin->_flags & _IO_UNBUFFERED) //判断标准输入流的缓冲区类型
        printf("unbuffered/n");
    else if(stdin->_flags & _IO_LINE_BUF)
        printf("line-buffered/n");
    else
        printf("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)); //输出文件描述符,应该为0
   
    printf("stdout is ");
    if(stdout->_flags & _IO_UNBUFFERED)//判断标准输出流的缓冲区类型
        printf("unbuffered/n");
    else if(stdout->_flags & _IO_LINE_BUF)
        printf("line-buffered/n");
    else
        printf("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)); //输出文件描述符,应该为1
   
    printf("stderr is ");
    if(stderr->_flags & _IO_UNBUFFERED) //判断标准出错流的缓冲区类型
        printf("unbuffered/n");
    else if(stderr->_flags & _IO_LINE_BUF)
        printf("line-buffered/n");
    else
        printf("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)); //输出文件描述符,应该为2

    return 0;
}

 

gcc buf.c -o buf

./buf

看看结果

 

然后看看重定向对结果的影响

./buf <in.txt 1>out.txt 2>err.txt

 

无论是否使用重定向,标准出错都是无缓冲的

 

 

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值