aboutsummaryrefslogtreecommitdiff
path: root/slurp.c
blob: 122580659cd01f9159e4647ee938cd79c443375e (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
#include <stdio.h>
#include <stdlib.h>

#define BUFFER_STEP 1024

char *slurp(FILE *f, size_t *size)
{
	char *buffer = NULL;
	size_t nread = 0;

	buffer = malloc(BUFFER_STEP);
	if (!buffer) {
		perror("malloc");
		return NULL;
	}

	while (!feof(f)) {
		nread = fread(&buffer[*size], 1, BUFFER_STEP, f);
		*size += nread;
		buffer = realloc(buffer, *size);
		if (!buffer) {
			perror("realloc");
			return NULL;
		}
	}
	if (ferror(f)) {
		perror("slurp/fread");
	}
	return buffer;
}