Search code examples
cstderr

What is the difference between stdout and stderr in C?


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?


Solution

  • 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.