Created
August 19, 2014 23:08
-
-
Save 1995eaton/96d08e6f7265b2a2de9a to your computer and use it in GitHub Desktop.
Brainfuck interpreter in C++
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <cstring> | |
#include <fstream> | |
#define MAX_LINE 2048 | |
#define DATA_ALLOC 30000 | |
using namespace std; | |
void fuck(char *start, char *end) { | |
static char data[DATA_ALLOC]; | |
static char *ptr = data; | |
char *bstart, *bend; | |
size_t depth = 0; | |
while (start < end) { | |
char ch = *start; | |
if (depth) { | |
if (ch == '[') { | |
depth++; | |
} else if (ch == ']') { | |
depth--; | |
} | |
if (depth == 0) { | |
while (*ptr) { | |
fuck(bstart, bend); | |
} | |
} else { | |
bend++; | |
} | |
} else { | |
switch (ch) { | |
case '[': | |
depth++; | |
bstart = start + 1; | |
bend = start + 2; | |
break; | |
case '+': | |
++*ptr; | |
break; | |
case '-': | |
--*ptr; | |
break; | |
case '>': | |
++ptr; | |
break; | |
case '<': | |
--ptr; | |
break; | |
case '.': | |
cout << *ptr; | |
break; | |
case ',': | |
*ptr = getchar(); | |
break; | |
} | |
} | |
start++; | |
} | |
} | |
void fuck(string input) { | |
char *cstr = (char*) input.c_str(); | |
fuck(cstr, cstr + input.size()); | |
} | |
string read_file(string name) { | |
fstream stream(name, ios_base::in); | |
string result, line; | |
string valid_chars = "[].,-+<>"; | |
while (getline(stream, line)) { | |
for (const auto& c: line) { | |
if (valid_chars.find(c) != -1) { | |
result.append(sizeof(char), c); | |
} | |
} | |
} | |
stream.close(); | |
return result; | |
} | |
int main(int argc, char **argv) { | |
fuck(read_file(argv[1])); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment