-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmisc.c
102 lines (72 loc) · 1.56 KB
/
misc.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
#include "misc.h"
/* Ugly hack for C89 conformance. May not work everywhere. */
#ifndef va_copy
# ifdef __va_copy
# define va_copy(a,b) __va_copy((a),(b))
# else
# define va_copy(a,b) ((a) = (b))
# endif
#endif
void system_error(const char *msg) {
perror(msg);
abort();
}
void custom_warn(const char *format, ...) {
va_list ap;
va_start(ap, format);
vfprintf(stderr, format, ap);
va_end(ap);
fprintf(stderr, "\n");
}
/* TODO: factor with custom_warn */
void custom_error(const char *format, ...) {
va_list ap;
va_start(ap, format);
vfprintf(stderr, format, ap);
va_end(ap);
fprintf(stderr, "\n");
abort();
}
int asprintf(char **str, const char *format, ...) {
va_list ap;
int ret;
va_start(ap, format);
ret = avsprintf(str, format, ap);
va_end(ap);
return ret;
}
int avsprintf(char **str, const char *format, va_list ap) {
size_t size;
FILE *devnull;
int err;
va_list aq;
va_copy(aq, ap);
devnull = fopen("/dev/null", "w");
if (devnull == NULL)
system_error("/dev/null");
size = vfprintf(devnull, format, ap);
err = fclose(devnull);
if (err != 0)
system_error("close(\"/dev/null\")");
/* size++ for the final \0. */
size++;
*str = malloc(size * sizeof(char));
if (*str == NULL)
system_error("malloc");
size = vsprintf(*str, format, aq);
return size;
}
char *strdup(const char *str) {
size_t size;
char *ret;
size = strlen(str) + 1;
ret = malloc(size * sizeof(*ret));
if (ret == NULL)
system_error("malloc");
strcpy(ret, str);
return ret;
}