简体   繁体   English

为什么printf output正常没有fflush

[英]why does printf output normally without fflush

I learned that stdout is line buffered, and buffer is automatically flushed under several circumstances (1) when the buffer is full, (2) when print a \n character and the output is going to a "terminal" (eg is not being redirected to a file), (3) when the program exits, and (4) when the program is waiting for input.我了解到 stdout 是行缓冲的,并且在以下几种情况下会自动刷新缓冲区(1)当缓冲区已满时,(2)当打印一个 \n 字符并且 output 将进入“终端”时(例如没有被重定向到文件),(3)程序退出时,以及(4)程序等待输入时。 but when I use printf without \n,without fflush in a while loop,it outputs normally in every iteration,do I misunderstands how printf or fflush works?但是当我在没有 \n 的情况下使用 printf 时,在 while 循环中没有 fflush 时,它在每次迭代中都能正常输出,我是否误解了 printf 或 fflush 的工作原理? code was compiled and run on windows,I tryed the same code on ubuntu machine,it works fine,so is it a problem with terminal on windows?代码在 windows 上编译并运行,我在 ubuntu 机器上尝试了相同的代码,它工作正常,那么 windows 上的终端有问题吗?

int main(){
    int a=10;  
    while(a--){
        printf("hello world");
        sleep(1);
    }
    return 0;
}

According to Posix, in C, stdout may be line-buffered and subject to the worst-case latency you describe.根据 Posix,在 C 中,stdout 可能是行缓冲的,并且会受到您描述的最坏情况延迟的影响。 There is no requirement that it must be so.没有要求必须如此。

Many programming languages have a function called 'printf';许多编程语言都有一个名为“printf”的 function; which do you refer to?你指的是哪个? Looks like C from your example.从您的示例中看起来像 C 。


I just looked at the source code for printf for the C runtime library for some 2011-ish version of Visual Studio (the latest I happen to have to hand), and based on a very cursory scan of the code (it's quite complicated with all its preprocessor conditionalization), I'd say it buffers during execution and then flushes the buffer at the end of the call, for both stdout and stderr.我只是查看了 C 运行时库的 printf 的源代码,用于一些 2011-ish 版本的 Visual Studio(我碰巧必须手头的最新版本),并且基于对代码的非常粗略的扫描(所有这些都非常复杂)它的预处理器条件化),我会说它在执行期间缓冲,然后在调用结束时刷新缓冲区,用于标准输出和标准错误。

If you want to write portable code, you should not assume the above.如果你想编写可移植的代码,你不应该假设以上。 To ensure data written to stdout (without a line terminator) becomes visible, you should explicitly flush.为了确保写入标准输出(没有行终止符)的数据变得可见,您应该显式刷新。

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

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