I have just learned about stream buffering in C. As I understand, printf()
in C is buffered and it only prints when it hits a new line, the buffer is full or when we flush stdout
manually. Then I try these lines of code:
#include <stdio.h>
int main() {
printf("Hello world");
while(1);
}
Theoretically, the console will be received nothing, since Hello world
is still in the buffer. But for some reasons, my console still show this string. Why is it like that?
EDIT: I am using the command prompt in Windows 10.
CodePudding user response:
printf()
in C is buffered and it only prints when it hits a new line
Not quite.
Streams are commonly 1 of 3 modes: unbuffered, fully buffered, line buffered. Often stdout
is line buffered, flushing data when printing a '\n'
, its internal buffer is full or due to explicit commands like fflush(stdout)
.
Yet C specifies about these 3 modes: Support for these characteristics is implementation-defined. C17dr § 7.21.3 3.
Thus both seeing output and not seeing output are compliant for OP's code.
To ensure output is seen, flush. Otherwise, live with implementation defined behavior.
printf("Hello world");
fflush(stdout); // add
while(1);
CodePudding user response:
I'm not sure what part of the C standard you were reading, but the behavior you are seeing in Windows is correct according to Microsoft's documentation of their C runtime library:
Files opened using the stream routines are buffered by default. The stdout and stderr functions are flushed whenever they are full or, if you are writing to a character device, after each library call.
That documentation also links to a Microsoft-specific setvbuf
function you can use to control the buffering if you want. I generally just let the runtime library use its default settings and then I call fflush(stdout)
explicitly at every place where I want to ensure the output is flushed.