1 | /* careful.c --- I/O functions that do error checking. |
---|
2 | Jim Blandy <jimb@cyclic.com> --- February 1995 */ |
---|
3 | |
---|
4 | #include <string.h> |
---|
5 | #include <errno.h> |
---|
6 | #include <stdio.h> |
---|
7 | |
---|
8 | static char *prog_name; |
---|
9 | |
---|
10 | /* Use NAME as the name of the program in future error reports. |
---|
11 | If NAME is a filename containing slashes, only the last component |
---|
12 | of the path is used; this means that you can pass in argv[0], and |
---|
13 | still get clean error messages. |
---|
14 | Return the portion of NAME that will be used in error messages. */ |
---|
15 | char * |
---|
16 | careful_prog_name (char *name) |
---|
17 | { |
---|
18 | prog_name = strrchr (name, '/'); |
---|
19 | if (prog_name) |
---|
20 | prog_name++; |
---|
21 | else |
---|
22 | prog_name = name; |
---|
23 | |
---|
24 | return prog_name; |
---|
25 | } |
---|
26 | |
---|
27 | |
---|
28 | void |
---|
29 | check_syscall (int call, char *filename, char *op) |
---|
30 | { |
---|
31 | if (call != -1) |
---|
32 | return; |
---|
33 | |
---|
34 | fprintf (stderr, "%s: %s%s", |
---|
35 | prog_name, |
---|
36 | filename ? filename : "", |
---|
37 | filename ? ": " : ""); |
---|
38 | perror (op); |
---|
39 | |
---|
40 | exit (2); |
---|
41 | } |
---|
42 | |
---|
43 | |
---|
44 | /* If an error has occured on F, print an error message mentioning |
---|
45 | FILENAME and OP, as with check_syscall, and exit. If no error has |
---|
46 | occurred on F, simply return. */ |
---|
47 | void |
---|
48 | check_file (FILE *f, char *filename, char *op) |
---|
49 | { |
---|
50 | if (ferror (f)) |
---|
51 | check_syscall (-1, filename, op); |
---|
52 | } |
---|
53 | |
---|
54 | |
---|
55 | /* If NAME is null, return DEFALT. |
---|
56 | If NAME is non-null, try to open it with MODE; print an error message |
---|
57 | and exit if this doesn't succeed. */ |
---|
58 | FILE * |
---|
59 | careful_open (char *name, char *mode, FILE *defalt) |
---|
60 | { |
---|
61 | if (name) |
---|
62 | { |
---|
63 | FILE *result = fopen (name, mode); |
---|
64 | |
---|
65 | if (! result) |
---|
66 | { |
---|
67 | fprintf (stderr, "%s: ", prog_name); |
---|
68 | perror (name); |
---|
69 | exit (2); |
---|
70 | } |
---|
71 | |
---|
72 | return result; |
---|
73 | } |
---|
74 | else |
---|
75 | return defalt; |
---|
76 | } |
---|
77 | |
---|
78 | |
---|
79 | /* If FILE is neither stdin nor stdout, close it. */ |
---|
80 | void |
---|
81 | careful_close (FILE *f, char *filename) |
---|
82 | { |
---|
83 | check_file (f, filename, "closing file"); |
---|
84 | |
---|
85 | if (f != stdin && f != stdout) |
---|
86 | if (fclose (f) == EOF) |
---|
87 | check_syscall (-1, filename, "closing file"); |
---|
88 | } |
---|