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

#include "util.h"

int
read_file(char *path, char **output, size_t * read_size)
{
	long 	file_size;
	FILE   *fp;

	fp = fopen(path, "r");
	if (fp == NULL)
		return -1;

	/* get file size */
	if (fseek(fp, 0L, SEEK_END) != 0)
		return -1;

	file_size = ftell(fp);
	if (file_size < 0)
		return -1;

	/* rewind to file start */
	if (fseek(fp, 0L, SEEK_SET) != 0)
		return -1;

	/* create output buffer */
	*output = malloc(sizeof(char) * (file_size + 1));
	if (*output == NULL)
		return -1;

	/* read the file */
	*read_size = fread(*output, sizeof(char), file_size, fp);
	if (*read_size == 0 || ferror(fp) != 0) {
		free(*output);
		return -1;
	}
	/* enforce string termination */
	(*output)[*read_size] = '\0';

	return 0;
}

char   *
v_strcpy(char *str, size_t len)
{
	char   *new_str;
	size_t 	new_len;

	new_str = (char *) malloc(sizeof(char) * (len + 1));
	if (new_str == NULL)
		return NULL;

	new_len = strlcpy(new_str, str, len + 1);
	if (new_len >= len + 1) {
		free(new_str);
		return NULL;
	}
	return new_str;
}