简体   繁体   English

printf 刷新问题

[英]printf flush problem

I am modifying a big C code.我正在修改一个大的 C 代码。 For test purposes I had to redirect stdout to a file.出于测试目的,我不得不将标准输出重定向到一个文件。 I used this code snipped for this purpose: fp=freopen("OUT", "w",stdout) Now all printf calls will write to fp.我为此目的使用了这段代码: fp=freopen("OUT", "w",stdout)现在所有 printf 调用都将写入 fp。 It is a big code so I do not want to search all of the exit points and close the file before each exit.这是一个很大的代码,所以我不想搜索所有的退出点并在每次退出之前关闭文件。 What happens if do not close the file?如果不关闭文件会怎样? Is there a way to make it autoflush each time I write something to the file?每次我向文件写入内容时,有没有办法让它自动刷新?

setvbuf is probably the way to go: setvbuf可能是 go 的方式:

setvbuf (fp, NULL, _IONBF, 0);

This will turn off buffering altogether.这将完全关闭缓冲。 Just be prepared for the inevitable performance hit.只需为不可避免的性能冲击做好准备。

You also need to be aware that this will flush only at the runtime-library level in many systems, it will not necessarily cause a flush to the storage medium, as the UNIX fsync(fileno(fp)) would try to do.您还需要注意,这只会在许多系统中的运行时库级别刷新,它不一定会导致对存储介质的刷新,因为 UNIX fsync(fileno(fp))会尝试这样做。

So, while it will be okay if your program crashes, it will not help if the whole OS falls in a screaming heap.所以,虽然你的程序崩溃没关系,但如果整个操作系统陷入尖叫堆,那就无济于事了。 But then you probably have bigger problems than losing a little bit of output:-)但是你可能会遇到比失去一点 output 更大的问题:-)


But, unless your program is crashing, you probably shouldn't worry about it.但是,除非您的程序崩溃,否则您可能不应该担心它。 ISO C99 says, in part, that one of the actions of exit() , and hence returning from main() , is: ISO C99 部分表示exit()的动作之一,因此从main()返回,是:

Next, all open streams with unwritten buffered data are flushed, all open streams are closed, ...接下来,所有带有未写入缓冲数据的打开流都被刷新,所有打开的流都被关闭,......

So your data will be output regardless in that case.所以你的数据将是 output 无论如何。

Yes.是的。 Use setvbuf with _IONBF :setvbuf_IONBF一起使用:

setvbuf(stdout, 0, _IONBF, 0);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM