-
Notifications
You must be signed in to change notification settings - Fork 0
/
translator.c
90 lines (68 loc) · 2 KB
/
translator.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
#include <stdio.h>
#include <stdlib.h>
const char BPROG_BEGGINING[] =
"#include <stdio.h>\n\nint main() {\nchar array[30000] = {0};\nchar *ptr = "
"&array[0];\n\n";
const char BPROG_END[] = "\nreturn 0;\n}";
int main(int argc, char **argv) {
if (argc != 3) {
return 1;
}
FILE *input = fopen(argv[1], "r");
FILE *output = fopen(argv[2], "w");
fwrite(BPROG_BEGGINING, sizeof(char), sizeof(BPROG_BEGGINING)-1, output);
char buffer = '\0';
short commentFlag = 0;
while ((buffer = fgetc(input))) {
// putchar(buffer);
if (buffer == -1)
break;
if (commentFlag) {
fputc(buffer, output);
if (buffer == '\n')
commentFlag = 0;
continue;
}
switch (buffer) {
case '+':
fwrite("++*ptr;\n\0", sizeof(char), 8, output);
break;
case '-':
fwrite("--*ptr;\n\0", sizeof(char), 8, output);
break;
case '>':
fwrite("++ptr;\n\0", sizeof(char), 7, output);
break;
case '<':
fwrite("--ptr;\n\0", sizeof(char), 7, output);
break;
case '.':
fwrite("putchar(*ptr);\n\0", sizeof(char), 15, output);
break;
case ',':
fwrite("*ptr=getchar();\n\0", sizeof(char), 16, output);
break;
case '[':
fwrite("while (*ptr) {\n\0", sizeof(char), 15, output);
break;
case ']':
fwrite("}", sizeof(char), 1, output);
break;
case '*':
commentFlag = 1;
fwrite("//\0", sizeof(char), 2, output);
break;
case ' ':
break;
case '\n':
break;
default:
return 2;
break;
}
}
fwrite(BPROG_END, sizeof(char), sizeof(BPROG_END)-1, output);
fclose(input);
fclose(output);
return 0;
}