forked from leahneukirchen/mblaze
-
Notifications
You must be signed in to change notification settings - Fork 0
/
slurp.c
53 lines (47 loc) · 755 Bytes
/
slurp.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
#include <sys/stat.h>
#include <sys/types.h>
#include <errno.h>
#include <fcntl.h>
#include <stdlib.h>
#include <unistd.h>
int
slurp(char *filename, char **bufo, off_t *leno)
{
int fd;
struct stat st;
ssize_t nread = 0;
ssize_t n;
int r = 0;
fd = open(filename, O_RDONLY);
if (fd < 0) {
r = errno;
goto out;
}
if (fstat(fd, &st) < 0) {
r = errno;
goto out;
}
*bufo = malloc(st.st_size + 1);
if (!*bufo) {
r = ENOMEM;
goto out;
}
do {
if ((n = read(fd, *bufo + nread, st.st_size - nread)) < 0) {
if (errno == EINTR) {
continue;
} else {
r = errno;
goto out;
}
}
if (!n)
break;
nread += n;
} while (nread < st.st_size);
*leno = nread;
(*bufo)[st.st_size] = 0;
out:
close(fd);
return r;
}