Search code examples
cioprintf

Is printf buffering part of the C standard?


I am writing a program in C on Linux where various things will be written to stdout via printf. Naturally, I would try to minimize the IO calls and buffer all the information and then pass it to a single print call. However, through testing, I have discovered that printf does buffering of its own until it reaches a '\n'. My question is, can I be certain that all printf implementations do this, or is glibc just optimized? Is it reliable to trust printf to do the buffering for me?


Solution

  • The C standard allows both unbuffered and buffered streams. The relevant part is C17 7.21.3/3:

    When a stream is unbuffered, characters are intended to appear from the source or at the destination as soon as possible. Otherwise characters may be accumulated and transmitted to or from the host environment as a block. When a stream is fully buffered, characters are intended to be transmitted to or from the host environment as a block when a buffer is filled. When a stream is line buffered, characters are intended to be transmitted to or from the host environment as a block when a new-line character is encountered.

    This is typically a decision depending on the OS rather than the standard library implementation. Most hosted console-based OS use the line buffered implementation where \n will "flush the buffer". Otherwise an explicit call to fflush(stdout) will always do that (and it's strictly speaking more portable).

    An example of an unbuffered system is limited "bare metal" microcontroller one, where stdout is an UART and there's no hardware buffers to store a lot of characters.