Created
November 13, 2011 19:44
-
-
Save scruffyfox/1362566 to your computer and use it in GitHub Desktop.
Brainfuck Interpreter
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 <stdio.h> | |
static unsigned char cell[30000]; | |
static unsigned char *ptr; | |
void processCommand(char command, FILE *file) | |
{ | |
char cmd; | |
long pos; | |
switch (command) | |
{ | |
case '+': | |
{ | |
++*ptr; | |
break; | |
} | |
case '-': | |
{ | |
--*ptr; | |
break; | |
} | |
case '>': | |
{ | |
++ptr; | |
break; | |
} | |
case '<': | |
{ | |
--ptr; | |
break; | |
} | |
case '.': | |
{ | |
putchar(*ptr); | |
break; | |
} | |
case ',': | |
{ | |
*ptr = getchar(); | |
break; | |
} | |
case '[': | |
{ | |
pos = ftell(file); | |
while(*ptr) | |
{ | |
fseek(file, pos, SEEK_SET); | |
cmd = getc(file); | |
while (cmd != ']' && cmd != EOF) | |
{ | |
processCommand(cmd, file); | |
cmd = getc(file); | |
} | |
} | |
} | |
} | |
} | |
int main(int argc, char *argv[], char **envp[]) | |
{ | |
ptr = &cell[0]; | |
if (argc < 2) | |
{ | |
return 0; | |
} | |
else | |
{ | |
FILE *bf = fopen(argv[1], "r"); | |
char cmd; | |
while ((cmd = getc(bf)) != EOF) | |
{ | |
processCommand(cmd, bf); | |
} | |
fclose(bf); | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment