summaryrefslogtreecommitdiff
path: root/doc/slurp.c
blob: f0b047dbcdc1ebc986ca83cb7e5840a8c5b79674 (plain)
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
static void *p_slurp(const char *file, size_t *outsize)
{
	struct stat sb;
	int ret = 0, fd = open(file, O_RDONLY | O_BINARY);
	void *buf = NULL;
	ssize_t rdret;

	if (fd < 0) {
		fprintf(stderr, "ERROR: Slurping %s failed: %s\n",
		        file, strerror(errno));
		return NULL;
	}
	if (fstat(fd, &buf) < 0) {
		ret = errno;
		perror("fstat");
		goto out;
	}
	*outsize = sb.st_size; /* truncate if need be */
	buf = malloc(*outsize);
	if (buf == NULL) {
		ret = errno;
		perror("malloc");
		goto out;
	}
	rdret = read(fd, buf, *outsize);
	if (rdret < 0) {
		ret = errno;
		perror("read");
		free(buf);
	} else {
		*outsize = rdret;
	}
 out:
	close(fd);
	errno = ret;
	return buf;
}