-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbrainfuckstack.c
87 lines (77 loc) · 1.5 KB
/
brainfuckstack.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
#include "stdio.h"
#include "stdlib.h"
#include "stdint.h"
void runner();
unsigned int ramindex = 256;
unsigned int ram[1048832] = {0};
FILE *pc;
struct Stack {
unsigned int top;
unsigned int* array;
};
struct Stack* loop;
unsigned int ss = 0;
void push(struct Stack* stack, unsigned int item){
stack->array[++stack->top] = item;
ss++;
}
unsigned int pop(struct Stack* stack){
ss--;
return stack->array[stack->top--];
}
int main(int argc, char *argv[]) {
loop = (struct Stack*)malloc(sizeof(struct Stack));
loop->top = -1;
loop->array = (unsigned int*)malloc(4000000*sizeof(unsigned int));
if (argc != 2) {
printf("Not 1 argument\n");
exit(0);
}
pc = fopen(argv[1], "r");
if (pc == NULL) {
printf("Error opening file\n");
exit(0);
}
while (!feof(pc)) {
runner();
}
}
void runner() {
char c = fgetc(pc);
switch (c) {
case '>':
++ramindex;
break;
case '<':
--ramindex;
break;
case '+':
++ram[ramindex];
break;
case '-':
--ram[ramindex];
break;
case '.':
printf("%c", ram[ramindex]);
break;
case ',':
ram[ramindex] = getchar();
break;
case '[':
if(ram[ramindex] == 0){
while(fgetc(pc) != ']'){}
}
push(loop, ftell(pc));
break;
case ']':
if (ram[ramindex] != 0) {
// -1 because fgetc(pc) gets the next character
int popped = pop(loop)-1;
fseek(pc,popped,SEEK_SET);
return;
}
// Pops the ] pc off the stack when hitting 0
pop(loop);
break;
}
}