使用缓冲区的目的:尽量减少使用read/write的调用
分类:
1. Fully buffered means that I/O takes place only when the buffer is fully, the process explicitly calls fflush, or the process terminates by calling exit. A common size for the standard I/O buffer is 8192 bytes;
2. Line buffered means that I/O takes place when a newline is encountered, when the process calls fflush, or when the process terminates by calling exit.
3. Unbuffered means that I/O take place each time a standard I/O output function is called.
Most unix implementations of the standard I/O libarary use the following rules.
1. Standard error is always unbuffered. 能够快速显示错误
2. Standard input and standard output are fully buffered, unless they refer to a terminal device, in which case, they are line buffered.
3. All other streams are fully buffered unless they refer to a terminal device,
in which case, they are line buffered.
使用setbuf()和setvbuf()可以更改缓冲的类型:
setbuf(FILE *fp, char *buf) buf用malloc()开辟,当buf为NULL时,缓冲区为不带缓冲
setvbuf(FILE *fp,char *buf, int buf_mode, int size)
buf_mde有三种:_IOFBF 0 全缓冲, _IOLBF 1 行缓冲, _IONBF 2 不带缓冲
在任何时刻,可以使用fflush强制刷新一个数据流,此函数使该流所有未写的数据都被传递至内核。
由于fflush(stdin)的移植性不好,gcc不支持,故可以用以下代码清空stdin缓冲区:
while ((c = getchar()) != '\n' && c != EOF);
阅读(3974) | 评论(0) | 转发(0) |