In C, stdout
and stderr
both print to the console window by default. Is there any difference between stderr
and stdout
other than the level of buffering?
One of the differences between stdout
and stderr
is the level of buffering. In §7.21.3 Files ¶7, the C11 standard says:
At program startup, three text streams are predefined and need not be opened explicitly -- standard input (for reading conventional input), standard output (for writing conventional output), and standard error (for writing diagnostic output). As initially opened, the standard error stream is not fully buffered; the standard input and standard output streams are fully buffered if and only if the stream can be determined not to refer to an interactive device.
Typically, that means that standard output is line buffered (so the data is flushed when a newline is printed, or when the buffer is full), whereas standard error is either line buffered or unbuffered. These characteristics can be changed, of course.
The purpose of the standard error stream is to separate error messages from regular output. This is important in contexts such as shell scripts, where the standard output might be sent to a pipe or to a file. That redirection leaves standard error still going to a different place — usually the terminal. You can capture the standard output separately from the standard error too, at least if the shell is sufficiently powerful.
program > file
program | filter
program 2> error.log | filter
program > file 2> error.log
program 2> error.log
The first two leave the error messages visible on the terminal. The last three capture the error messages in the file error.log
— sending the standard output to the filter
program, the file
or to the terminal window respectively.
By separating the error messages from the standard output, the programs down the pipeline (filter
in my example) don't have to interpret the error messages from program
, which makes them much, much simpler.
If running a program from the console, or via a batch file, or via a shortcut, use > or 1> to redirect stdout to a file, and use 2> to redirect stderr to a file. For example if reading from stdin, and writing to both stdout and stderr:
myprog <input.txt >output.txt 2>error.txt
or if you want stdout to a file, but stderr to display on the screen, use:
myprog <input.txt >output.txt
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With