-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbrainf.c
More file actions
100 lines (96 loc) · 2.16 KB
/
brainf.c
File metadata and controls
100 lines (96 loc) · 2.16 KB
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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
#include <stdio.h>
#include <stdlib.h>
long forward(char *src, size_t len, long src_ix) {
long depth = 1;
while (depth > 0) {
src_ix++;
if (src_ix >= len) {
puts("Out of Bounds");
exit(-1);
}
switch (src[src_ix]) {
case '[':
depth += 1;
break;
case ']':
depth -= 1;
break;
default:;
}
}
return src_ix;
}
long backward(char *src, size_t len, long src_ix) {
long depth = 1;
while (depth > 0) {
src_ix--;
if (src_ix < 0) {
puts("Out of Bounds");
exit(-1);
}
switch (src[src_ix]) {
case '[':
depth -= 1;
break;
case ']':
depth += 1;
break;
default:;
}
}
return src_ix;
}
void brainf(char *src, size_t len) {
char *mem = calloc(30000, sizeof(char));
long src_ix = 0;
long mem_ix = 0;
while (src_ix < len) {
switch (src[src_ix]) {
case '+':
mem[mem_ix]++;
break;
case '-':
mem[mem_ix]--;
break;
case '>':
mem_ix = (mem_ix + 1) % 30000;
break;
case '<':
if (mem_ix == 0) {
mem_ix = 29999;
} else {
mem_ix--;
}
break;
case '.':
printf("%c", mem[mem_ix]);
break;
case ',':
scanf("%c", &mem[mem_ix]);
break;
case '[':
if (mem[mem_ix] == 0)
src_ix = forward(src, len, src_ix);
break;
case ']':
if (mem[mem_ix] != 0)
src_ix = backward(src, len, src_ix);
break;
default:;
}
src_ix++;
}
}
int main(int argc, char *argv[]) {
if (argc != 2) {
puts("usage: ./brainf <filepath>");
return 0;
}
FILE *f = fopen(argv[1], "r");
fseek(f, 0L, SEEK_END);
long size = ftell(f);
char buffer[size];
rewind(f);
size_t len = fread(buffer, sizeof(char), size, f);
brainf(buffer, len);
}