why does printf output normally without fflush

Viewed 63

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;
}
1 Answers

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.

Related