-
Notifications
You must be signed in to change notification settings - Fork 1
/
brainfunk.cpp
132 lines (121 loc) · 1.91 KB
/
brainfunk.cpp
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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
#include "libbrainfunk.hpp"
#include <getopt.h>
using std::fstream;
using std::cin;
using std::cout;
using std::string;
using std::endl;
using std::cerr;
/* Read code and filter out unnecessary characters */
void readcode(string &code, string filename)
{
fstream input;
input.open(filename);
if (!input.is_open())
{
perror(filename.c_str());
exit(1);
}
char c;
while(input.get(c))
{
switch(c)
{
case '+':
case '-':
case '>':
case '<':
case '[':
case ']':
case '.':
case ',':
code += c;
break;
default:
break;
}
}
input.close();
}
void helpmsg(int argc, char **argv)
{
cerr << "Usage: " << argv[0] << " [-h] [-m mode] [-s code string] [-f file] [-o out]" << endl;
}
int main(int argc, char **argv)
{
string code;
string mode = "bf";
ostream *output = &cout;
bool valid = false;
int opt;
while((opt = getopt(argc, argv, "hm:s:f:o:")) != -1)
{
switch(opt)
{
case 'f':
readcode(code, optarg);
valid = true;
break;
case 's':
code = optarg;
valid = true;
break;
case 'h':
helpmsg(argc, argv);
return 0;
break;
case 'm':
mode = optarg;
break;
case 'o': // Output file
try
{
if(strcmp(optarg, "-") == 0)
output = &cout;
else
output = new fstream(optarg, fstream::out);
}
catch(const std::exception& e)
{
std::cerr << e.what() << '\n';
}
break;
default:
break;
}
}
if(!valid)
{
cerr << "No input specified." << endl;
helpmsg(argc, argv);
return 1;
}
class Brainfunk bf(MEMSIZE);
try
{
bf.translate(code);
if(mode == "bf")
{
bf.run();
}
else if(mode == "bit")
{
bf.dump(*output, FMT_BIT);
}
else if(mode == "bfc")
{
bf.dump(*output, FMT_C);
}
else
{
cerr << "Unknown mode: " << mode << endl;
return 1;
}
bf.clear();
}
catch(const std::exception& e)
{
std::cerr << e.what() << '\n';
}
return 0;
}