Sams Teach Yourself C in 21 Days

(singke) #1
18: printf(“errno = %d.\n”, errno);
19: exit(1);
20: }
21: else
22: {
23: puts(“File opened for reading.”);
24: fclose(fp);
25: }
26: return 0;
27: }

Enter file name: perror.c
File opened for reading.
Enter file name: notafile.xxx
You goofed!: No such file or directory
errno = 2.
This program prints one of two messages based on whether a file can be opened
for reading. Line 15 tries to open a file. If the file opens, the elsepart of the if
loop executes, printing the following message:
File opened for reading.
If there is an error when the file is opened, such as the file not existing, lines 17–19 of
theifloop execute. Line 17 calls the perror()function with the string “You goofed!”.
The error number is then printed. The result of entering a file that does not exist is
You goofed!: No such file or directory.
errno = 2

548 Day 19

LISTING19.4 continued

OUTPUT

ANALYSIS

DOcheck for possible errors in your pro-
grams. Never assume that everything is
okay.

DON’Tinclude the errno.h header file if
you aren’t going to use the symbolic
error constants listed in Table 19.2.

DO DON’T


Searching and Sorting ........................................................................................


Among the most common tasks that programs perform are searching and sorting data.
The C standard library contains general-purpose functions that you can use for each task.

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

Free download pdf