-
Notifications
You must be signed in to change notification settings - Fork 63
/
Copy pathutil.h
59 lines (48 loc) · 1.01 KB
/
util.h
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
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
// prints to stderr than exits with code 1
static inline
void err(const char * const msg)
{
fprintf(stderr, "%s\n", msg);
exit(1);
}
// returns a heap allocated string, caller needs to free
static inline
char *read_file(const char * const filename)
{
if (filename == NULL) return NULL;
FILE *fp = fopen(filename, "r");
if (fp == NULL) return NULL;
assert(!fseek(fp, 0, SEEK_END));
long file_size = ftell(fp);
rewind(fp);
size_t code_size = sizeof(char) * file_size;
char *code = malloc(code_size);
if (code == NULL) return NULL;
fread(code, 1, file_size, fp);
assert(!fclose(fp));
return code;
}
#define STACKSIZE 100
struct stack {
int size;
int items [STACKSIZE];
};
static inline
int stack_push(struct stack * const p, const int x)
{
if (p->size == STACKSIZE)
return -1;
p->items[p->size++] = x;
return 0;
}
static inline
int stack_pop(struct stack * const p, int *x)
{
if (p->size == 0)
return -1;
*x = p->items[--p->size];
return 0;
}