Error Message to stdout

The three standard I/O devices are stdin, stdout, and stderr. They represent the devices for standard input, standard output, and standard error messages. While you might see plenty of examples of stdin and stdout, examples of stderr are less common, although they don’t have to be.

Internally, the three standard devices are aliased to specific file handles recognized by the operating system. They are typically 0, 1, 2 for stdin, stdout, and stderr, respectively. They could also be file handles 1, 2, 3. Regardless, the names are aliased and you should use the aliases, which are defined in stdio.h.

stdin is the standard input device, the keyboard.

stdout is the standard output device, the display. Years ago it would have been a printer or a teletype, which brings up the interesting point about both stdin and stdout: They can be reassigned.

I/O redirection commands are used at the command prompt to mess with standard input and output. For example, you can send output to a file or fetch input from some other device. The operating system handles the specifics. As programmer, you mustn’t make assumptions when you code about where I/O may come or go.

That is, unless you use the stderr device.

stderr is an output device, similar to stdout. In fact, it’s pretty much the same as stdout, but unlike that device the output sent to stderr cannot be redirected. It always goes to the standard output device, which these days is the display.

Because it can’t be redirected, the stderr device is ideal for displaying errors and other messages that must be seen. Use it in your code for such messages, as shown in the following code.

#include <stdio.h>

int main()
{
    FILE *fh;

    fh = fopen("blorfus","r");
    if( fh == NULL )
    {
        fprintf(stderr,"Unable to open that file!\n");
        return;
    }
    fclose(fh);

    return(0);
}

In the above listing, the error message is sent to the stdout device by the fprintf() function at Line 10. That message always goes to the display (or standard output device) regardless of how badly the program is mangled by I/O redirection.

I’ve not heard of an input device similar to stderr, nor can I reason why such a thing would be needed. I can also strongly recommend that you don’t use stderr to display regular messages. By doing so you would make your program less useful to others, users who rely on I/O redirection to run their computer systems.

Leave a Reply