2

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" (e.g. is not being redirected to a file), (3) when the program exits, and (4) when the program is waiting for input. 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? 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?

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

1 Answers1

0

According to Posix, in C, stdout may be line-buffered and subject to the worst-case latency you describe. There is no requirement that it must be so.

Many programming languages have a function called 'printf'; which do you refer to? Looks like C from your example.


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.

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.

user13784117
  • 1,124
  • 4
  • 4
  • It's C,are you suggesting that the stdout on windows is not line buffered?otherwise I don't know how to explain the result from my code... – codesavesworld Jul 12 '20 at 07:06
  • I'm suggesting that the word "problem", as used in your posting, is not appropriate. The effect of line buffering output is to potentially delay the appearance of the output, but such delay is not guaranteed, and code should not rely on it. But back when I programmed on WIndows, the C RTL source code was included in the Visual Studio installation. You can check. – user13784117 Jul 12 '20 at 12:50