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

来源:互联网 发布:苹果mac air截屏 编辑:程序博客网 时间:2024/05/14 18:45

原文:点击打开链接

基于流的操作最终都会调用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