Course Content
Programming in C
About Lesson

In the previous section, we shared an implementation of cat command-line utility. Out error-handling is very basic in the code. We just print the message to standard output if we can’t open the file. This would get merged with other output. This might be acceptable when the output is being displayed on the screen, but not if it’s going to a file or another program via a pipeline.

We could use stderr to handle such error messages. stderr is a second output stream and output written to stderr usually appears on the screen, even if the standard output is redirected.

fprintf(stderr, "Can't open file.");

We could use the standard library function exit to terminate the program execution, when called. The argument of exit is available to whatever process called this one, so the success or failure of the program can be tested by another program that uses this one as a sub-process.
Conventionally, a return value of 0 signals normal termination; non-zero values suggest abnormal situations. exit calls fclose for each open output file, to flush out any buffered output.

Within main,

return expr;

is equivalent to

exit(expr);
Scroll to Top