source: tags/initial/ALEIO/careful.c

Last change on this file was 2, checked in by oldcode, 24 years ago

Initial revision

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 1.8 KB
Line 
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
8static 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.  */
15char *
16careful_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
28void
29check_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.  */
47void
48check_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.  */
58FILE *
59careful_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.  */
80void
81careful_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}
Note: See TracBrowser for help on using the repository browser.