-
Notifications
You must be signed in to change notification settings - Fork 0
/
brainf.c
79 lines (69 loc) · 2.03 KB
/
brainf.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
72
73
74
75
76
77
78
79
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#define MEMORY_SIZE 30000
int main(int argc, char** argv) {
if (argc != 2) {
fprintf(stderr, "usage: %s file\n", argv[0]);
return 1;
}
// loading program file
FILE* file = fopen(argv[1], "r");
if (file == NULL) {
fprintf(stderr, "%s: cannot open file\n", argv[0]);
return 1;
}
fseek(file, 0, SEEK_END);
long program_len = ftell(file);
fseek(file, 0, SEEK_SET);
char* program = calloc(program_len, sizeof(char));
fread(program, sizeof(char), program_len, file);
fclose(file);
// brainfuck interpretation
uint8_t mem[MEMORY_SIZE] = {0}; // memory
int ptr = 0; // pointer to memory
int pc = 0; // program counter
while (program[pc] != '\0') {
switch (program[pc]) {
case '>': ptr += 1; break;
case '<': ptr -= 1; break;
case '+': mem[ptr] += 1; break;
case '-': mem[ptr] -= 1; break;
case '.': putchar(mem[ptr]); fflush(stdout); break;
case ',': mem[ptr] = getchar(); break;
case '[': {
if (mem[ptr] == 0) {
// finding the corresponding closing bracket:
int count = 1;
while (count) {
pc += 1;
if (program[pc] == '[') {
count += 1;
}
if (program[pc] == ']') {
count -= 1;
}
}
}
} break;
case ']': {
// finding the corresponding opening bracket:
int count = 1;
while (count) {
pc -= 1;
if (program[pc] == ']') {
count += 1;
}
if (program[pc] == '[') {
count -= 1;
}
}
continue;
} break;
default: break; // ignoring all other characters
}
pc += 1;
}
free(program);
return 0;
}