Does printf always flush the buffer on encountering a newline?

No, the standard says that stdout is initially fully buffered if the output device can be determined to be a non-interactive one.

It means that, if you redirect stdout to a file, it won’t flush on newline. If you want to try and force it to line-buffered, use setbuf or setvbuf.

The relevant part of C99, 7.19.3 Files, paragraph 7, states:

At program startup, three text streams are predefined and need not be opened explicitly – standard input (for reading conventional input), standard output (for writing conventional output), and standard error (for writing diagnostic output). As initially opened, the standard error stream is not fully buffered; the standard input and standard output streams are fully buffered if and only if the stream can be determined not to refer to an interactive device.

Just keep in mind section 5.1.2.3/6:

What constitutes an interactive device is implementation-defined.

Leave a Comment