aboutsummaryrefslogtreecommitdiff
path: root/src/drain.h
blob: d0f1111f5f1a0d2931b6d9e2842972b8da172f32 (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
#pragma once
#include <stdio.h>
#include <stdlib.h>

static char *
drain(FILE *fp, long *size)
{
	if (fseek(fp, 0, SEEK_END) < 0) {
		perror("drain:SEEK_END");
		return NULL;
	}
	*size = ftell(fp);
	if (fseek(fp, 0, SEEK_SET) < 0) {
		perror("drain:SEEK_SET");
		return NULL;
	}
	char *const s = malloc(*size + 1);
	if (s == NULL) {
		perror("drain:malloc");
		return NULL;
	}
	if ((long)fread(s, 1, *size, fp) != *size) {
		perror("drain:fread");
		free(s);
		return NULL;
	}
	s[*size] = '\0';
	return s;
}