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
|
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "util.h"
/* This isn't a 1:1 wrapper around fgets. It also removes that annoying
* trailing \n automatically */
char *
xfgets(char *s, size_t size, FILE *stream)
{
char *p;
if ((s = fgets(s, size, stream))) {
if ((p = strchr(s, '\n')))
*p = '\0';
} else if (ferror(stream)) {
fprintf(stderr, "fgets: %s\n", strerror(errno));
exit(1);
}
return s;
}
FILE *
xfopen(const char *pathname, const char *mode)
{
FILE *f;
if ((f = fopen(pathname, mode)) == NULL) {
fprintf(stderr, "%s: %s\n", pathname, strerror(errno));
exit(1);
}
return f;
}
int
xfputs(const char *s, FILE *stream)
{
int d;
if ((d = fputs(s, stream)) == EOF) {
fprintf(stderr, "fputs: %s\n", strerror(errno));
exit(1);
}
return d;
}
void *
xmalloc(size_t size)
{
void *n;
if ((n = malloc(size)) == NULL) {
fprintf(stderr, "malloc: %s\n", strerror(errno));
exit(1);
}
return n;
}
void *
xrealloc(void *ptr, size_t size)
{
void *n;
if ((n = realloc(ptr, size)) == NULL) {
fprintf(stderr, "malloc: %s\n", strerror(errno));
exit(1);
}
return n;
}
/* strlcpy is unportable, and strncpy is a mess. So we define our own strlcpy
* instead. */
size_t
my_strlcpy(char *dst, const char *src, size_t size)
{
const char *p2;
char *p1, *stop;
p1 = dst;
p2 = src;
stop = dst + size;
while (*p2 && p1 != stop)
*p1++ = *p2++;
*p1 = '\0';
return (size_t)(p1 - dst);
}
|