《Unix环境高级编程》这本书附带了许多短小精美的小程序,我在阅读此书的时候,将书上的代码按照自己的理解重写了一遍(大部分是抄书上的),加深一下自己的理解(纯看书太困了,呵呵)。此例子在Ubuntu10.04上测试通过。
程序简介:这个程序会为三个标准流及一个与普通文件相关联的流打印有关缓冲的状态信息。
//《APUE》:程序5-3 //对各个标准I/O流打印缓冲状态 #include <stdio.h> #include <unistd.h> #include <libio.h> #include <stdlib.h> void pr_stdio(const char *, FILE *); int main(void) { FILE *fp; fputs("enter any character\n", stdout); if( getchar() == EOF ) { fprintf(stderr, "Getchar error\n"); exit(1); } fputs("one line to standard error\n", stderr); pr_stdio("stdin", stdin); pr_stdio("stdout", stdout); pr_stdio("stderr", stderr); //我的系统上找不到/etc/motd这个文件,所以用一个普通的txt文件代替 fp = fopen("output.txt", "r"); if( NULL == fp ) { fprintf(stderr, "fopen error\n"); exit(1); } if( EOF == getc(fp) ) { fprintf(stderr, "getc error\n"); exit(1); } pr_stdio("output.txt", fp); return 0; } void pr_stdio(const char *name, FILE *fp) { printf("stream = %s, ", name); if( fp->_IO_file_flags & _IO_UNBUFFERED ) printf("unbuffered"); else if( fp->_IO_file_flags & _IO_LINE_BUF ) printf("line buffered"); else printf("fully buffered"); printf(", buffer size = %d\n", fp->_IO_buf_end - fp->_IO_buf_base); }
运行示例(红色的为输入):
qch@ubuntu:~/code$ gcc temp.c -o temp
qch@ubuntu:~/code$ ./temp
enter any character
(键入回车键)
one line to standard error
stream = stdin, line buffered, buffer size = 1024
stream = stdout, line buffered, buffer size = 1024
stream = stderr, unbuffered, buffer size = 1
stream = output.txt, fully buffered, buffer size = 4096
qch@ubuntu:~/code$ ./temp < output.txt > std.out 2>std.err
qch@ubuntu:~/code$ cat std.err
one line to standard error
qch@ubuntu:~/code$ cat std.out
enter any character
stream = stdin, fully buffered, buffer size = 4096
stream = stdout, fully buffered, buffer size = 4096
stream = stderr, unbuffered, buffer size = 1
stream = output.txt, fully buffered, buffer size = 4096
结论:从此可见,该系统默认的是:当标准输入,输出连终端时,它们是行缓冲的。行缓冲的长度是1024;当将这个流重定向到文件时,它们就变成全缓冲的,其缓冲区的长度是该文件系统优先选用的I/O长度;还有,标准出错是非缓冲的,而普通文件被系统默认是全缓冲的。