-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.c
108 lines (89 loc) · 2.1 KB
/
main.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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define ARRAYSIZE 30000
unsigned char tape[ARRAYSIZE] = {0};
unsigned char *ptr = tape;
//searches forward for matching bracket
int findbracket(char *commands, int currentpos){
int lb = 0;
int rb = 0;
for(int i = currentpos; i < strlen(commands); ++i){
if(commands[i] == '[') ++lb;
if(commands[i] == ']') ++rb;
if(lb == rb){
return i;
}
}
}
//executes brainfuck commands in a string
void interpret(char *commands){
int stack[10];
int *pStack = stack;
for(int i = 0; i < strlen(commands); ++i){
char command = commands[i];
if(command == '>'){
++ptr;
}
else if(command == '<'){
--ptr;
}
else if(command == '+'){
++*ptr;
}
else if(command == '-'){
--*ptr;
}
else if(command == '.'){
putchar(*ptr);
}
else if(command == ','){
*ptr = getchar();
}
else if(command == '['){
if(*ptr == 0){
i = findbracket(commands, i);
}
else{
++pStack;
*pStack = i;
}
}
else if(command == ']'){
if(*ptr != 0){
i = *pStack;
}
else{
--pStack;
}
}
}
}
int main(int argc, char const *argv[]){
const char *path = argv[1];
FILE *file = fopen(path, "r");
if(file == NULL){
printf("could not open file\n");
return 1;
}
int n = 1;
char *content = (char *)malloc(n *sizeof(char));
if(content == NULL){
printf("out of memory\n");
return 1;
}
int c;
while((c = getc(file)) != EOF){
content[n-1] = c;
++n;
content = realloc(content, n * sizeof(char));
if(content == NULL){
printf("out of memory\n");
return 1;
}
}
interpret(content);
fclose(file);
free(content);
return 0;
}