参考资料:
https://q16964777.iteye.com/blog/2228244
知道缓冲有几种模式:无缓冲、行缓冲、全缓冲。通过判断FILTE中的 _flags 的判断可以知道究竟是那种缓冲模式。
#include <stdio.h> int stream_attribute(FILE *fp) { if(fp->_flags & _IO_UNBUFFERED) { printf("The IO type is unbuffered\n"); }else if(fp->_flags & _IO_LINE_BUF){ printf("The IO type is line buf\n"); }else{ printf("The IO type is full buf\n"); } printf("The IO size : %d\n",fp->_IO_buf_end - fp->_IO_buf_base); return 0; } int main() { FILE *fp; stream_attribute(stdin); printf("___________________________________\n\n"); stream_attribute(stdout); printf("___________________________________\n\n"); stream_attribute(stderr); printf("___________________________________\n\n"); if((fp = fopen("test.txt","w+")) == NULL) { perror("fail to fopen"); } stream_attribute(fp); return 0; } 我们修改一下代码再看 #include <stdio.h> int stream_attribute(FILE *fp) { if(fp->_flags & _IO_UNBUFFERED) { printf("The IO type is unbuffered\n"); }else if(fp->_flags & _IO_LINE_BUF){ printf("The IO type is line buf\n"); }else{ printf("The IO type is full buf\n"); } printf("The IO size : %d\n",fp->_IO_buf_end - fp->_IO_buf_base); return 0; } int main() { FILE *fp; getchar(); stream_attribute(stdin); printf("___________________________________\n\n"); stream_attribute(stdout); printf("___________________________________\n\n"); stream_attribute(stderr); printf("___________________________________\n\n"); if((fp = fopen("test.txt","w+")) == NULL) { perror("fail to fopen"); } printf("before write:\n"); stream_attribute(fp); fputc('a',fp); printf("after write:\n"); stream_attribute(fp); return 0; }
另外要清楚,缓冲区是在执行读写操作之后才分配的。