Skip to content

Instantly share code, notes, and snippets.

@kleczkowski
Last active August 22, 2016 23:12
Show Gist options
  • Save kleczkowski/48cd4de333f694979ccf94df54f1631d to your computer and use it in GitHub Desktop.
Save kleczkowski/48cd4de333f694979ccf94df54f1631d to your computer and use it in GitHub Desktop.
Simple Brainfuck interpreter as fuck.
#include <stdio.h>
#include <stdlib.h>
void interpret(const char *code);
int main(int argc, char **argv) {
char *file_contents;
long input_file_size;
FILE *input_file;
if (argc < 2) {
printf("Using: bfck <source code path>\n");
return 1;
}
input_file = fopen(argv[1], "rb");
if (ferror(input_file)) {
printf("can't open source file : %s", argv[1]);
return 1;
}
fseek(input_file, 0, SEEK_END);
input_file_size = ftell(input_file);
rewind(input_file);
file_contents = (char *) malloc((input_file_size + 1) * sizeof(char));
fread(file_contents, sizeof(char), input_file_size, input_file);
fclose(input_file);
file_contents[input_file_size] = 0;
interpret(file_contents);
free(file_contents);
}
void interpret(const char *code) {
char buf[64 * 1024];
char *p = buf;
int l = 0;
for (; *code; code++) {
switch (*code) {
case '>': p++; break;
case '<': p--; break;
case '+': (*p)++; break;
case '-': (*p)--; break;
case '.': putchar(*p); break;
case ',': *p = (char) getchar(); break;
case '[':
if (!*p) {
code++;
while (l > 0 || *code != ']') {
switch (*code) {
case '[':
l++; break;
case ']':
l--; break;
default: break;
}
code++;
}
}
break;
case ']':
if (*p) {
code--;
while (l > 0 || *code != '[') {
switch (*code) {
case '[':
l++; break;
case ']':
l--; break;
default: break;
}
code--;
}
code--;
}
break;
default: break;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment