-
-
Notifications
You must be signed in to change notification settings - Fork 2
/
brainfuck interpreter.c
67 lines (49 loc) · 1.13 KB
/
brainfuck interpreter.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
#include <stdio.h>
#include <stdlib.h>
int interpreter(FILE *src);
int main(int argc, char *argv[]) {
if (argc != 2) {
fprintf(stderr, "Usage: bf <file>\n");
exit(1);
}
FILE *fp = fopen(argv[1], "r");
if (!fp) {
fprintf(stderr, "Could not open brainfuck file %s :(\n", argv[1]);
exit(2);
}
return interpreter(fp);
}
int interpreter(FILE *src) {
char c;
int mem = 0, code = 0;
char memory[3001];
fseek(src, 0, SEEK_END);
int src_len = ftell(src);
char *source = (char*)malloc(src_len);
rewind(src);
for (int i = 0; i < src_len; i++) {
source[i] = fgetc(src);
}
while (code >= 0 && code < src_len) {
char ch = source[code];
if (ch == '.') {
printf("%c", memory[mem]);
}
if (ch == ',') {
memory[mem] = fgetc(stdin);
}
if (ch == '+') {
memory[mem]++;
}
if (ch == '-') {
memory[mem]--;
}
if (ch == '>') {
mem++;
}
if (ch == '<') {
mem--;
}
}
return 0;
}