What are the rules of automatic stdout buffer flushing in C?

ghz 1years ago ⋅ 6463 views

Question

I'm just curious which conditions should be satisfied to flush stdout buffer automatically.

First of all I was confused that this pseudo code doesn't print output every iteration:

while (1) {
    printf("Any text");
    sleep(1);
}

But if I add newline character it will.

After few experiments i found that on my machine stdout buffer is flushed:

  1. When I put to stdout 1025 characters or more;
  2. When I read stdin;
  3. When I put newline character to stdout;

The first condition is totally clear - when the buffer is full it should be flushed. The second one is also reasonable. But why newline character causes flushing? What are the others implicit conditions for this?


Answer

Rules of automatic flushing stdout buffer is implementation-defined (ID). It is ID when the stream is unbuffered , fully buffered , or line buffered.

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. Furthermore, characters are intended to be transmitted as a block to the host environment when a buffer is filled, when input is requested on an unbuffered stream, or when input is requested on a line buffered stream that requires the transmission of characters from the host environment.

Support for these characteristics is implementation-defined , ... C11dr §7.21.3 3


I'm just curious which conditions should be satisfied to flush stdout buffer automatically.

If code wants to insure output is certainly flushed, use fflush(). Other conditions that may automatically flush the stream are implementation defined.