基于流的操作最终都会调用read或write进行操作。即流的内部封装了这两个系统调用。
缓冲分如下三种:
全缓冲(相应宏_IO_FULL_BUF):直到缓冲区被填满,菜调用系统I/O函数。磁盘文件读写通常是全缓冲的。
行缓冲(相应宏_IO_LINE_BUF):直到遇到换行符'/n',才调用系统I/O函数。标准输入输出都是行缓冲的。
无缓冲(相应宏_IO_UNBUFFERED):没有缓冲,数据立即读入或输出到外存文件和设备上。例如标准出错。相应宏_IO_UNBUFFERED
在判断流用的是那种缓冲时,应将文件流对象中的缓冲区标志与该宏“与”操作,判断结果是否为0就行了。
范例:
//buf.c
#include <stdio.h>
int main(void)
{
printf("stdin is ");
if(stdin->_flags & _IO_UNBUFFERED) //判断标准输入流的缓冲区类型
printf("unbuffered/n");
else if(stdin->_flags & _IO_LINE_BUF)
printf("line-buffered/n");
else
printf("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)); //输出文件描述符,应该为0
printf("stdout is ");
if(stdout->_flags & _IO_UNBUFFERED)//判断标准输出流的缓冲区类型
printf("unbuffered/n");
else if(stdout->_flags & _IO_LINE_BUF)
printf("line-buffered/n");
else
printf("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)); //输出文件描述符,应该为1
printf("stderr is ");
if(stderr->_flags & _IO_UNBUFFERED) //判断标准出错流的缓冲区类型
printf("unbuffered/n");
else if(stderr->_flags & _IO_LINE_BUF)
printf("line-buffered/n");
else
printf("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)); //输出文件描述符,应该为2
return 0;
}
gcc buf.c -o buf
./buf
看看结果
然后看看重定向对结果的影响
./buf <in.txt 1>out.txt 2>err.txt
无论是否使用重定向,标准出错都是无缓冲的。