Skip to content

Instantly share code, notes, and snippets.

@scruffyfox
Created November 13, 2011 19:44
Show Gist options
  • Save scruffyfox/1362566 to your computer and use it in GitHub Desktop.
Save scruffyfox/1362566 to your computer and use it in GitHub Desktop.
Brainfuck Interpreter
#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