blob: 1e7940e024b88b1ab29720a12bee410267235350 (
plain)
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 <stdlib.h>
#include <stdio.h>
#define SIZE 1024
struct stack {
long int data;
struct stack *next;
};
void push(struct stack **s, long int i) {
struct stack *nuevo = malloc(sizeof(struct stack));
nuevo->data = i;
nuevo->next = *s;
*s = nuevo;
}
void pop(struct stack **s) {
struct stack *temp = *s;
*s = (*s)->next;
free(temp);
}
int main(int argc, char **argv) {
if (argc != 2) return 1;
FILE *source = fopen(argv[1], "r");
if (!source) return 1;
struct stack *open_brackets = 0;
char tape[SIZE] = {0};
char *curr = tape;
int lineNr = 1;
int exit = 0;
while (!feof(source) && !exit) {
char c = fgetc(source);
switch (c) {
case '\n':
lineNr++;
break;
case '+':
*curr += 1;
break;
case '-':
*curr -= 1;
break;
case '>':
if (curr != &tape[SIZE - 1]) curr++;
else curr = &tape[0];
break;
case '<':
if (curr != &tape[0]) curr--;
else curr = &tape[SIZE - 1];
break;
case '.':
putchar(*curr);
break;
case ',':
*curr = getchar();
break;
case '[':
if (*curr) {
push(&open_brackets, ftell(source));
}
else {
int counter = 1;
while (counter > 0 && !feof(source)) {
c = fgetc(source);
if (c == '[') counter++;
else if (c == ']') counter--;
}
if (feof(source)) {
printf("Error: Can't find matching ']' at line %d\n", lineNr);
exit = 1;
}
}
break;
case ']':
if (*curr && open_brackets) {
fseek(source, open_brackets->data, SEEK_SET);
}
else if (open_brackets){
pop(&open_brackets);
}
else {
printf("Error: Can't find matching '[' at line %d\n", lineNr);
exit = 1;
}
}
}
if (open_brackets) {
lineNr = 1;
rewind(source);
while (ftell(source) != open_brackets->data) {
if (fgetc(source) == '\n') lineNr++;
}
printf("Error: Can't find matching ']' at line %d\n", lineNr);
while (open_brackets) pop(&open_brackets);
exit = 1;
}
fclose(source);
return exit;
}
|