cstdoutstdinfflush

why the execution order of output is not as expected


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)


Solution

  • 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