Question

I know the the messages to be displayed is buffered in stdout. But consider the following code:

#include <stdio.h>

int main()
{
    while(true)
    {
        printf("Buffered, will be flushed");
    }
}

I think that the message doesn't display until the newline is reached. But in this case we have that the pack of the messages will be displayed.

Was it helpful?

Solution

Buffers aren't infinite in size. If you output more than the buffer's size, it will be flushed automatically, and you'll see a bunch of messages all at once (repeatedly here).

Here's how the C standard describes the various forms of buffering (C11 draft n1570, §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. 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, and may be affected via the setbuf and setvbuf functions.

Emphasis added. POSIX has essentially the same definition, which you can browse online in the Standard I/O Streams chapter.

Standard output is usually line buffered.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top