OSDN Git Service

Initial commit.
[crnpred/crnpred.git] / src / eprintf.c
1 /* Copyright (C) 1999 Lucent Technologies */
2 /* Excerpted from 'The Practice of Programming' */
3 /* by Brian W. Kernighan and Rob Pike */
4
5 #include <stdio.h>
6 #include <stdlib.h>
7 #include "eprintf.h"
8 #include <stdarg.h>
9 #include <string.h>
10 #include <errno.h>
11
12 static char *name = NULL;  /* program name for messages */
13
14 /* eprintf: print error message and exit */
15 void eprintf(char *fmt, ...)
16 {
17         va_list args;
18
19         fflush(stdout);
20         if (progname() != NULL)
21                 fprintf(stderr, "%s: ", progname());
22
23         va_start(args, fmt);
24         vfprintf(stderr, fmt, args);
25         va_end(args);
26
27         if (fmt[0] != '\0' && fmt[strlen(fmt)-1] == ':')
28                 fprintf(stderr, " %s", strerror(errno));
29         fprintf(stderr, "\n");
30         exit(2); /* conventional value for failed execution */
31 }
32
33 /* weprintf: print warning message */
34 void weprintf(char *fmt, ...)
35 {
36         va_list args;
37
38         fflush(stdout);
39         fprintf(stderr, "warning: ");
40         if (progname() != NULL)
41                 fprintf(stderr, "%s: ", progname());
42         va_start(args, fmt);
43         vfprintf(stderr, fmt, args);
44         va_end(args);
45         if (fmt[0] != '\0' && fmt[strlen(fmt)-1] == ':')
46                 fprintf(stderr, " %s\n", strerror(errno));
47         else
48                 fprintf(stderr, "\n");
49 }
50
51 /* emalloc: malloc and report if error */
52 void *emalloc(size_t n)
53 {
54         void *p;
55
56         p = malloc(n);
57         if (p == NULL)
58                 eprintf("malloc of %u bytes failed:", n);
59         return p;
60 }
61
62 /* erealloc: realloc and report if error */
63 void *erealloc(void *vp, size_t n)
64 {
65         void *p;
66
67         p = realloc(vp, n);
68         if (p == NULL)
69                 eprintf("realloc of %u bytes failed:", n);
70         return p;
71 }
72
73 /* estrdup: duplicate a string, report if error */
74 char *estrdup(char *s)
75 {
76         char *t;
77
78         t = (char *) malloc(strlen(s)+1);
79         if (t == NULL)
80                 eprintf("estrdup(\"%.20s\") failed:", s);
81         strcpy(t, s);
82         return t;
83 }
84
85 /* progname: return stored name of program */
86 char *progname(void)
87 {
88         return name;
89 }
90
91 /* setmyprogname: set stored name of program */
92 void setmyprogname(char *str)
93 {
94         name = estrdup(str);
95 }