Andrii Zymohliad Andrii Zymohliad - 1 year ago 72
C Question

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

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");

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 Source

See the man page for setbuf(3). By default, stdout is set to line buffering mode.

printf() and its variants work with buffered output, and delegate to write(). So this buffering is controlled by the C library implementation of printf, with the buffer and buffer settings located in the FILE structure.

It's also worth noting the difference between section 3 and section 2 of the unix man pages. Section 2 is made up of function calls that directly talk to the operating system and do things that it would otherwise be impossible to do from a pure user program. Section 3 is made up of function calls that a user could reproduce on their own, which often delegate to section 2 calls. Section 2 functions contain the low-level "magic" that allow C programs to interact with the outside world and perform I/O. Section 3 functions can provide a more convenient interface to the section 2 functions.

printf, scanf, getchar, fputs, and other FILE * functions all are section 3 functions that delegate to write() and read(), which are section 2 functions. read() and write() do not buffer. printf() interacts with the buffer in the FILE structure, and occasionally decides to send the contents of that buffer out through write().

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download