-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcommon.c
71 lines (58 loc) · 1.25 KB
/
common.c
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
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include "common.h"
void error(const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
fprintf(stderr, "error: ");
vfprintf(stderr, fmt, ap);
fprintf(stderr, "\n");
va_end(ap);
}
void fatal(const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
fprintf(stderr, "fatal: ");
vfprintf(stderr, fmt, ap);
fprintf(stderr, "\n");
va_end(ap);
exit(1);
}
int read_file(const char *filename,
void **buffer, size_t *size)
{
FILE *fp;
void *buf;
size_t sz;
fp = fopen(filename, "r");
if (!fp) {
error("could not open file `%s' for reading", filename);
return FALSE;
}
if (fseek(fp, 0L, SEEK_END) < 0) {
fclose(fp);
error("error during seek of `%s`", filename);
return FALSE;
}
sz = (size_t) ftell(fp);
rewind(fp);
buf = malloc(sz);
if (!buf) {
fclose(fp);
error("could not allocate memory");
return FALSE;
}
if (fread(buf, 1, sz, fp) != sz) {
fclose(fp);
free(buf);
error("could not read `%s'", filename);
return FALSE;
}
fclose(fp);
buffer[0] = buf;
size[0] = sz;
return TRUE;
}