linux - [Solved-5 Solutions] Why does printf not flush after the call unless a newline is in the format string ? - ubuntu - red hat - debian - linux server - linux pc
Linux - Problem :
Why does printf not flush after the call unless a newline is in the format string ?
Linux - Solution 1:
Print to stderr instead using fprintf:
Flush stdout whenever you need it to using fflush:
You can also disable buffering on stdout by using setbuf :
Linux - Solution 2:
It's probably like that because of efficiency and because if you have multiple programs writing to a single TTY, this way you don't get characters on a line interlaced. So if program A and B are outputting, you'll usually get:
This stinks, but it's better than
Linux - Solution 3:
To immediately flush call fflush(stdout) or fflush(NULL) - NULL means flush everything.
Linux - Solution 4:
stdout is buffered, so will only output after a newline is printed.
To get immediate output, either:
- Print to stderr.
- Make stdout unbuffered.
Linux - Solution 5:
You can fprintf to stderr, which is unbuffered, instead. On the other hand you can flush stdout when you want to. Or you can set stdout to unbuffered.