summaryrefslogtreecommitdiff
path: root/src/utils.c
blob: fdc6aea01e9b841beed1f2bc1738a23e07c80981 (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
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
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "types.h"
#include "voxel.h"
#include "utils.h"

char *read_file(const char *filename)
{
	FILE *file;
	long length, read;
	char *buffer;

	file = fopen(filename, "r");
	if (file == NULL) {
		ERROR("could not read file: %s", filename);
		return NULL;
	}

	fseek(file, 0, SEEK_END);
	length = ftell(file);
	fseek(file, 0, SEEK_SET);

	buffer = malloc(length + 1);
	read = fread(buffer, 1, length, file);
	buffer[length] = 0;

	if (read < length) {
		ERROR("could not read file: %s", filename);
		free(buffer);
		return NULL;
	}

	fclose(file);
	return buffer;
}

_Noreturn void die(void)
{
	exit(1);
}

void *xalloc(usize size)
{
	void *ptr = malloc(size);
	if (ptr == NULL && size != 0)
		die();
	return ptr;
}

void *xrealloc(void *ptr, usize size)
{
	ptr = realloc(ptr, size);
	if (ptr == NULL && size != 0)
		die();
	return ptr;
}

void *xzalloc(usize size)
{
	void *ptr = xalloc(size);
	memset(ptr, 0, size);
	return ptr;
}