a note on the philosophy of Unix and stdin, stdout, and stderr
Please let me know if this is helpful or unhelpful. This probably should be put in some tutorial rather than here.
There is an underlying philosophy in Unix. Trying to state it simply, everything is a file. So any program gets its input from the input file and writes its output to an output file. If it encounters any problems, it writes a message to an error file.
Because of this underlying philosophy, any C program automatically assumes that you will need an input file, output file, and error file. So the compiler quietly opens these three file handles for you automatically. (FILE *)stdin is opened for reading. (FILE *)stdout and (FILE *)stderr are opened for writing. Therefore, you do not need to open these three files explicitly. In fact, it is an error to attempt to do so.
By default, the input file stdin is connected to the keyboard and output files stdout and stderr are connected to the console. The console was originally a teletype keyboard and printer, but on newfangled modern computers is more likely to be a keyboard and a video display screen.
Writing output to an open file handle uses the file print with format function fprintf( FILE *pfOutfile, const char *pcFormatString, ... ), where pfOutfile is a file pointer to a file open for output, pcFormatString is a format string (usually a string constant) which specifies the format of the output possibly including format specifiers for additional variables, and the ellipsis (...) is a possibly empty list of variables to be written to the output file.
Since we usually write to stdout, the shortened print function
printf( const char *pcFormatString, ... );
is provided which is synonymous with
fprintf( stdout, const char *pcFormatString, ... );
That is, the message print line in the hello, world program,
printf( "Hello, world. Go suck pond water. \n" );
is actually identical in meaning to
fprintf( stdout, "Hello, world. Go suck pond water. \n" );
Similarly, the scan with format function
scanf( const char *pcFormatString, ... )
is synonymous to file scan with format function
fscanf( stdin, const char *pcFormatString, ... )
Though you do not need to open stderr, you do need to specify it and use the fprintf() function, as in
fprintf( stderr, "error detected!" );
So what is the difference between stdout and stderr? Well, if you redirect the output of your program to an output file when you actually run it, the stderr messages still go to the console. As a matter of style, you should use stdout for normal output from your program and send error messages to stderr. You can redirect the error output written to stderr separately from the redirection of the normal output to stdout.
Last edited by ArthurSittler; 05-18-2010 at 02:21 PM.
|