Question

I have a good old C FILE file descriptor under Windows that is used by an output stream to write data to. My question is simple and yet I could not find the answer:

When is the content flushed to disc assuming I don't call fflush?

The stream constantly receives data and it seems that the content is flushed quite often, but what is the rule for flushing it?

Was it helpful?

Solution

If the library implementation can determine the output stream not to refer to an interactive device (and only then), the stream will be fully buffered, i.e. it will be flushed when the buffer (by default of BUFSIZ size) is full.

If not fully buffered, a stream can be line buffered, i.e. it will be flushed when an '\n' is written (or the buffer is full, if your line is really long), or unbuffered.

(ISO/IEC 9899:1999, chapter 7.19.5.3 "The fopen() function", paragraph 7. Don't have a newer version of the standard at hand, but AFAIK this didn't change.)

What constitutes an "interactive device" is implementation-defined. (Chapter 5.1.2.3 "Program execution", paragraph 6.)

The general idea is that file output should be fully buffered whereas terminal output be line buffered (or unbuffered, as Jesse Good correctly pointed out).

Both the buffering policy and the buffer size can be changed via setvbuf(). Note that any such change must happen before you start accessing the stream, which is somewhat obvious once you think about it.

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