简体   繁体   English

当 printf 可以自行打印时,为什么在 printf 之后使用 fflush?

[英]why use fflush after printf when printf can print by itself?

I'm new to C, sorry if my question is too basic.I often see code like:我是 C 新手,对不起,如果我的问题太基本了。我经常看到这样的代码:

printf("%d", counter);
fflush(stdout);

my guess is that it won't print output if the buffer is not full therefore you need to flush the stdout .我的猜测是,如果缓冲区未满,它将不会打印输出,因此您需要刷新stdout But I tried to not use fflush , only printf , I still have out put printed on the screen, then what's the point to use flush ?但是我尝试不使用fflush ,只使用printf ,我仍然在屏幕上打印出来,那么使用flush什么意义?

The main reason to use fflush after printf is timing.printf之后使用fflush主要原因是计时。

printf will display the information, at some point in time. printf将在某个时间点显示信息。 Basically all prints to printf are buffered.基本上所有到printf打印都被缓冲了。 fflush guarantees the buffer is emptied, meaning the print happened at the line of code that called fflush . fflush保证缓冲区被清空,这意味着打印发生在调用fflush的代码行。

In programs that tend to crash, fflush can be a very useful tool.在容易崩溃的程序中, fflush是一个非常有用的工具。 Often the message that a user of your program wishes to receive is the last message printed just before the crash.通常,程序用户希望收到的消息是崩溃前打印的最后一条消息。 If the program doesn't have a fflush that user will probably not get the last print statement, with the statement being lost in the buffer before display.如果程序没有fflush ,那么用户可能不会得到最后一个打印语句,因为该语句在显示前会丢失在缓冲区中。

This can often lead to developers looking in the wrong place in a program's source code for errors upon analyzing log files after a crash.这通常会导致开发人员在崩溃后分析日志文件时在程序源代码中的错误位置查找错误。 The mental process is "well, it couldn't have made it here, because there's a printf we would have seen" when the reality is the program passed the "would have been seen" printf statement but died with that message in the buffer.心理过程是“好吧,它不可能在这里成功,因为有一个我们会看到的printf ”,而现实是程序通过了“本来可以看到”的printf语句,但在缓冲区中因该消息而死亡。 If one flushes statements just after printing them, this doesn't happen (although the program runs slower, because flushing takes time).如果在打印语句后立即刷新语句,则不会发生这种情况(尽管程序运行速度较慢,因为刷新需要时间)。

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

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