Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between stdout and stderr in C?

Tags:

c

stderr

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?

like image 604
srilakshmikanthanp Avatar asked Dec 23 '22 19:12

srilakshmikanthanp


2 Answers

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.

like image 175
Jonathan Leffler Avatar answered Jan 16 '23 11:01

Jonathan Leffler


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
like image 38
rcgldr Avatar answered Jan 16 '23 12:01

rcgldr