1a89f9494578e65ca2c1f2a58b4f2f968b311cdb
[ccc.git] / util.c
1 #include <stdarg.h>
2 #include <stdlib.h>
3 #include <stdio.h>
4 #include <string.h>
5
6 void pdie(const char *msg)
7 {
8 perror(msg);
9 exit(1);
10 }
11
12 void die(const char *msg, ...)
13 {
14 va_list ap;
15 va_start(ap, msg);
16 vfprintf(stderr, msg, ap);
17 va_end(ap);
18 exit(1);
19 }
20
21 void pindent(int indent, FILE *out)
22 {
23 for (int i = 0; i<indent; i++)
24 if (fputc('\t', out) == EOF)
25 pdie("fputc");
26 }
27
28 void safe_fprintf(FILE *out, const char *msg, ...)
29 {
30 va_list ap;
31 va_start(ap, msg);
32 int r = vfprintf(out, msg, ap);
33 va_end(ap);
34 if (r < 0)
35 pdie("fprintf");
36 }
37
38 void *safe_malloc(size_t size)
39 {
40 void *res = malloc(size);
41 if (res == NULL)
42 pdie("malloc");
43 return res;
44 }
45
46 void *safe_strdup(const char *c)
47 {
48 char *res = strdup(c);
49 if (res == NULL)
50 pdie("strdup");
51 return res;
52 }