CITS2002 Systems Programming  
next CITS2002 CITS2002 schedule  

The two standard output streams - stdout and stderr

To date, most of our output has been produced using the function printf() which, by default, sends its output to the terminal screen.

Pedantically, printf() actually sends its output to the stdout (pronounced standard-output) stream which, by default, is connected to the screen, but may be redirected to a file or even to another program (using operating system features, not C features).

For example, on macOS and Linux:

prompt> mycc -o myprogram myprogram.c                                   
prompt> myprogram     # appears on the screen
prompt> myprogram  >  output.dat
prompt> myprogram  |  wc -l

Here, our program "doesn't care" where its output is going - to the default location (the screen), to a file, or through a pipe.
In our programs, we could choose to explicitly send to the stdout stream, instead of printf(), with:

fprintf(stdout, "a longhand mechanism, equivalent to calling printf\n"); 

stdout and stderr are two of the standard I/O streams that are created and initialized by the C runtime system when the execution of new C programs is commenced.

In general, we prefer to write "normal" output to stdout, and errors to stderr, and we'll adopt this practice in the rest of the unit.

FILE *fp = fopen("results.data", "w");

if(fp == NULL) {
    fprintf(stderr, "Cannot open results.data\n");                       
    exit(EXIT_FAILURE);
}
else {
    fprintf(fp, .....);                       
    .....
}

The standard perror() function (from Lecture-11) also sends its output to stderr.

 


CITS2002 Systems Programming, Lecture 19, p1, 7th October 2019.