summaryrefslogtreecommitdiff
path: root/src/util.c
blob: c88eb7b414465ed3d533aa00ab71b3bf99ab5d03 (plain) (blame)
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
#include <s.h>

#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "logerr.h"

#include "util.h"



int
slurp(const char *const filename, size_t *const outlen, char **out) {
	int rc = -1;

	FILE *file = NULL;
	char *str  = NULL;

	file = fopen(filename, "r");
	if (file == NULL) {
		logerr("fopen(): %s", strerror(errno));
		goto out;
	}

	if (fseek(file, 0L, SEEK_END)) {
		logerr("fseek(): %s", strerror(errno));
		goto out;
	}

	const long lsize = ftell(file);
	if (lsize == -1) {
		logerr("ftell(): %s", strerror(errno));
		goto out;
	}
	const size_t size = (size_t)lsize;

	errno = 0;
	rewind(file);
	if (errno) {
		logerr("rewind(): %s", strerror(errno));
		goto out;
	}

	str = malloc(size + NULL_TERMINATOR);
	if (str == NULL) {
		logerr("malloc(): %s", strerror(errno));
		goto out;
	}

	if (fread(str, sizeof(char), size, file) != size) {
		logerr("fread(): %s", strerror(errno));
		goto out;
	}
	str[size] = '\0';
	*out = str;
	*outlen = size;

	rc = 0;
out:
	if (file != NULL) {
		if (fclose(file)) {
			logerr("fclose(): %s", strerror(errno));
			rc = -1;
		}
	}
	if (rc) {
		if (str != NULL) {
			free(str);
			str = NULL;
		}
	}
	return rc;
}