user5917481
user5917481

Reputation:

Buffering stdin & stdout

I have this simple peace of code :

#include <stdio.h>

int main()
{
    fprintf(stdout , "stdout \n");
    fprintf(stderr , "stduerr \n");
    return 0;
}

Output:
stdout
stderr

I know that stdout is buffered and stderr is not and know a bout newline flushing

the result on Windows and netbeans is :

stdout
stderr

the result using mac and Eclipse :

stderr
stdout

and Want to know why ...

Thanks a lot ...

Upvotes: 2

Views: 1716

Answers (3)

mame98
mame98

Reputation: 1341

As others already noted, you will get the result you expected if you use

fprintf(stdout, "STDOUT");

fprintf(stderr, "STDERR");

This is because the default Linux terminal stdout is line buffered while stderr is not buffered.

You will need to flush stdout or to manually print a '\n' to stdout before the print to stderr. Then you will see it before the stderr message.

Note that it is also possible to turn off buffering for stdout.

Upvotes: 0

dan4thewin
dan4thewin

Reputation: 1184

With stdio(3) output streams that refer to terminal devices are line buffered like stdout, while stderr is not buffered.

The program above exits immediately after fprintf, so stdout is flushed then.

If you want to see the differences in behavior, redirect the stdout and stderr to a file, and add a few more fprintf lines.

Upvotes: 0

Magisch
Magisch

Reputation: 7352

stdout by default (on your system anyways) is line buffered, meaning it will flush either when you flush it, or when you put a newline character '\n' in it, which you do here:

fprintf(stdout , "stdout \n");

More on the buffering of stdout:

If stdout is known to not refer to an interactive device, the stream is fully buffered. Otherwise, it is library-dependent whether the stream is line buffered or not buffered by default (see setvbuf).

Source

Upvotes: 1

Related Questions