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:

fprintf(stderr, "I will be printed immediately");
click below button to copy the code. By - Linux tutorial - team

Flush stdout whenever you need it to using fflush:

printf("Buffered, will be flushed");
fflush(stdout); // Will now print everything in the stdout buffer
click below button to copy the code. By - Linux tutorial - team

You can also disable buffering on stdout by using setbuf :

setbuf(stdout, NULL);
click below button to copy the code. By - Linux tutorial - team

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:

program A output
program B output
program B output
program A output
program B output
click below button to copy the code. By - Linux tutorial - team

This stinks, but it's better than

proprogrgraam m AB  ououtputputt
prproogrgram amB A  ououtputtput
program B output
click below button to copy the code. By - Linux tutorial - team

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.


Related Searches to - linux - linux tutorial - Why does printf not flush after the call unless a newline is in the format string?