Programming in C

(Barry) #1

370 Chapter 16 Input and Output Operations in C


writes the indicated error message to stderrif the file datacannot be opened for read-
ing. In addition, if the standard output has been redirected to a file, this message still
appears in your window.

The exitFunction


At times, you might want to force the termination of a program, such as when an error
condition is detected by a program.You know that program execution is automatically
terminated whenever the last statement in mainis executed or when executing a return
from main.To explicitly terminate a program, no matter from what point you are exe-
cuting, the exitfunction can be called.The function call
exit (n);
has the effect of terminating (exiting from) the current program. Any open files are auto-
matically closed by the system.The integer value nis called the exit status, and has the
same meaning as the value returned from main.
The standard header file <stdlib.h>defines EXIT_FAILUREas an integer value that
you can use to indicate the program has failed and EXIT_SUCCESSto be one that you
can use to indicate it has succeeded.
When a program terminates simply by executing the last statement in main, its exit
status is undefined. If another program needs to use this exit status, you mustn’t let this
happen. In such a case, make certain that you exit or return from mainwith a defined
exit status.
As an example of the use of the exitfunction, the following function causes the pro-
gram to terminate with an exit status of EXIT_FAILUREif the file specified as its argu-
ment cannot be opened for reading. Naturally, you might want to return the fact that the
open failed instead of taking such a drastic action by terminating the program.
#include <stdlib.h>
#include <stdio.h>

FILE *openFile (const char *file)
{
FILE *inFile;

if ( (inFile = fopen (file, "r")) == NULL ) {
fprintf (stderr, "Can't open %s for reading.\n", file);
exit (EXIT_FAILURE);
}

return inFile;
}
Remember that there’s no real difference between exiting or returning from main.They
both terminate the program, sending back an exit status.The main difference between
exitand returnis when they’re executed from inside a function other than main.The
Free download pdf