2

I'm learning c and I got stuck in some codes as below from a tutorial.

#include <stdio.h>
 
int main() {
    fprintf(stdout, "This is to stdout. ");
    fprintf(stderr, "This is to stderr. ");
    fprintf(stdout, "This is also to stdout. ");
}

and the result they got is

This is to stderr. This is to stdout. This is also to stdout. 

which is out of order but what I got is

This is to stdout. This is to stderr. This is also to stdout.

which is in order. So that's so weird, Why I got a different result? (the tut I refer to is https://www.journaldev.com/39049/fflush-in-c)

o o
  • 145
  • 6

1 Answers1

4

Maybe in your implementation, stdout is unbuffered. Check your documentation.

You may want to try setvbuf() to revert stdout to line-buffered: use, for example, setvbuf(stdout, 0, _IOLBF, 1000); right at the beginning of main() before any other use of stdout.


Usually stdout is line-buffered and stderr is unbuffered.

unbuffered : data is sent, by the OS, from the stream to the device as soon as it is available.

line-buffered: data is sent to the device when a newline (or a limit) is reached.

fully buffered: data is sent to the device when the buffer is full.

fprintf(stdout, "hello"); // "hello" is kept in buffer because no newline
fprintf(stderr, "again"); // "again" is sent to the device immediately
fprintf(stdout, "world"); // "world" is kept in buffer
// ...
return 0;                 // buffer (now containing "helloworld") is sent to the device at program completion
pmg
  • 106,608
  • 13
  • 126
  • 198
  • It's not your "fault" :-) Some installations (especially with an IDE) change the default buffering mode of `stdout` (and maybe other streams). – pmg Jul 09 '21 at 09:26
  • I got another question, why the order doesn't back to "normal" after I add a newline right after "hello". (i.e.hello\n). – o o Jul 09 '21 at 10:06
  • 1
    Maybe your `stdout` is fully-buffered. Data is only sent to device when buffer (maybe 1K bytes?) is full. A newline should force data to the device when the stream is line-buffered! *But there can be various levels of buffering among the different interfaces data must pass trhough from your code to the device (code, implementation, OS, device software, device hardware, ...) and no real way to manage all this mess from your C code.* – pmg Jul 09 '21 at 10:23