《Unix環境高級編程》這本書附帶了許多短小精美的小程序,我在閱讀此書的時候,將書上的代碼按照自己的理解重寫了一遍(大部分是抄書上的),加深一下自己的理解(純看書太困了,呵呵)。此例子在Ubuntu 10.04上測試通過。
相關鏈接
- 《UNIX環境高級編程》(第二版)apue.h的錯誤 http://www.linuxidc.com/Linux/2011-04/34662.htm
- Unix環境高級編程 源代碼地址 http://www.linuxidc.com/Linux/2011-04/34826.htm
- //《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);
- }
運行示例(加下劃線的為輸入):
www.linuxidc.com @ubuntu:~/code$ gcc temp.c -o temp
www.linuxidc.com @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
www.linuxidc.com @ubuntu:~/code$ ./temp < output.txt > std.out 2>std.err
www.linuxidc.com @ubuntu:~/code$ cat std.err
one line to standard error
www.linuxidc.com @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長度;還有,標准出錯是非緩沖的,而普通文件被系統默認是全緩沖的。