summaryrefslogtreecommitdiff
path: root/igen/misc.c
blob: ba8c755bee77f76e81d511ec143ae5864afbdeb9 (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
66
67
68
69
70
71
72
73
74
75
76
77
#include <ctype.h>
#include <string.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include "misc.h"

char *read_file(const char *filename, long *size) {
	/* Open the file. */
	FILE *fp = fopen(filename, "r");
	/* Size of the file, in bytes. */
	long filesize = 0;
	/* Buffer of the file contents. */
	char *buf;

	/* Return NULL, if we couldn't open the file. */
	if (fp == NULL) {
		return NULL;
	}

	/* Return NULL, if we couldn't seek to the end of the file. */
	if (fseek(fp, 0L, SEEK_END)) {
		fclose(fp);
		return NULL;
	}

	/* Get the size of the file, in bytes. */
	filesize = ftell(fp);

	/* Return NULL, if the returned size is negative. */
	if (filesize < 0) {
		fclose(fp);
		return NULL;
	}

	/* Allocate enough space for the entire file, plus one. */
	buf = calloc(filesize+1, sizeof(char));

	/* Return NULL, if the buffer wasn't allocated. */
	if (buf == NULL) {
		fclose(fp);
		return NULL;
	}

	/* Seek back to the start of the file. */
	rewind(fp);
	/* Read the entire file contents into the buffer. */
	fread(buf, sizeof(char), filesize, fp);
	/* Close the file. */
	fclose(fp);

	/* Return the filesize, in bytes. */
	*size = filesize;
	/* Return the buffer. */
	return buf;
}

char *get_line(char **str) {
	char *s;
	size_t i;
	char *tmp = *str;

	for (i = 0; tmp[i] != '\n' && tmp[i] != '\0'; i++);

	s = calloc(i+1, sizeof(char));
	memcpy(s, *str, i);

	*str += (i+1);
	return s;
}

char *make_str(const char *str) {
	const size_t length = strlen(str);
	char *s = calloc(length+1, sizeof(char));
	memcpy(s, str, length+1);
	return s;
}