Sams Teach Yourself C in 21 Days

(singke) #1
Exploring the C Function Library 547

19


indication that an error occurred, you can test errno. If it’s nonzero, an error has
occurred, and the specific value of errnoindicates the nature of the error. Be sure to
reseterrnoto zero after handling the error. The next section explains perror(), and then
Listing 19.4 illustrates the use of errno.

Theperror()Function ................................................................................

Theperror()function is another of C’s error-handling tools. When called,perror()
displays a message on stderrdescribing the most recent error that occurred during a
library function call or system call. The prototype, in stdio.h, is
void perror(const char *msg);
The argument msgpoints to an optional, user-defined message. This message is printed
first, followed by a colon and the implementation-defined message that describes the
most recent error. If you call perror()when no error has occurred, the message dis-
played is no error.
A call to perror()does nothing to deal with the error condition. It’s up to the program
to take action. The action might consist of prompting the user to do something such as
terminate the program. The action the program takes can be determined by testing the
value of errnoand by the nature of the error. Note that a program need not include the
header file errno.h to use the external variable errno. That header file is required only if
your program uses the symbolic error constants listed in Table 19.2. Listing 19.4 illus-
trates the use of perror()anderrnofor handling runtime errors.

LISTING19.4 perror.c. Using perror()anderrnoto deal with runtime
errors
1: /* Demonstration of error handling with perror() and errno. */
2:
3: #include <stdio.h>
4: #include <stdlib.h>
5: #include <errno.h>
6:
7: int main( void )
8: {
9: FILE *fp;
10: char filename[80];
11:
12: printf(“Enter filename: “);
13: gets(filename);
14:
15: if (( fp = fopen(filename, “r”)) == NULL)
16: {
17: perror(“You goofed!”);

INPUT

30 448201x-CH19 8/13/02 11:20 AM Page 547

Free download pdf