首页 > 代码库 > 重定向输出遇到的缓冲问题

重定向输出遇到的缓冲问题

来源:http://blog.csdn.net/silyvin/article/details/8281342

一个项目中需要迭代计算,时间长,但是在重定向输出的时候所有标准输出不能及时输出,这就要求程序主函数正常运行完后才能正常输出到文件。

因为标准输出到终端时默认行缓冲或无缓冲,重定向到硬盘之后,就变成了全缓冲

 

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.
 

解决方法有 fflush  , setvbuf  ,  和伪终端

1. 每次printf时都刷新缓存区强制输出,fflush(stdout)

2. setvbuf 更改缓冲类型,手动设置缓冲区大小,使之足够小。

 

int setvbuf( FILE *stream, char *buffer, intmode, size_tsize );

 

The setvbuf function allows the program to control both buffering and buffer size forstream.stream must refer to an open file that has not undergone an I/O operation since it was opened. The array pointed to bybuffer is used as the buffer, unless it isNULL, in which casesetvbuf uses an automatically allocated buffer of lengthsize/2 * 2 bytes.

The mode must be _IOFBF_IOLBF, or _IONBF. If mode is _IOFBF or _IOLBF, then size is used as the size of the buffer. If mode is_IONBF, the stream is unbuffered andsize and buffer are ignored. Values formode and their meanings are:

_IOFBF

Full buffering; that is, buffer is used as the buffer andsize is used as the size of the buffer. Ifbuffer is NULL, an automatically allocated buffersize bytes long is used.

_IOLBF

With MS-DOS, the same as _IOFBF.

_IONBF

No buffer is used, regardless of buffer or size.

对于 _IOFBF _IOLBF ,dos上并没有区别,第四个参数size指定了缓冲区的大小,并且,当第二个参数,一个字符串buffer没有指定的情况下,系统将自动分配一片内存,长度为 (unsigned int)(size/2) * 2  ,每次向缓冲区写size个,大于缓冲区大小后,自动输出。

 

测试:

x.cpp

 

[cpp] view plain copy
 
  1. #include <stdio.h>  
  2. #include <windows.h>  
  3.   
  4. int main(int argc, char *argv[])  
  5. {  
  6.     setvbuf(stdout, 0, _IOFBF, <span style="color:#FF0000;">10</span>);  
  7.     printf("hello world\n");  
  8.     Sleep(10000000);  
  9.       
  10.     return 0;  
  11. }  


cl x.cpp
x > re.txt
pause

 

运行后直接退出

输出 hello worl

 

将10改成14后没有输出

改成4后输出 hello wo

 

在这个项目中 setvbuf(stdout, 0, _IONBF, 0);

 

重定向输出遇到的缓冲问题