Created
May 10, 2009 20:45
-
-
Save gerard/109727 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 <stdio.h> | |
#include <stdlib.h> | |
#include <unistd.h> | |
#include <fcntl.h> | |
#include <string.h> | |
#define BFSIZE 30000 | |
void fuck(int f) { | |
char c; | |
do read(f, &c, 1); | |
while(c != ']'); | |
} | |
void brain(int f, char v[], int *i) { | |
int fp; | |
char c; | |
while(read(f, &c, 1)) { | |
switch(c) { | |
case '+': | |
v[*i]++; | |
break; | |
case '-': | |
v[*i]--; | |
break; | |
case '>': | |
(*i)++; | |
break; | |
case '<': | |
(*i)--; | |
break; | |
case ',': | |
v[*i] = getchar(); | |
break; | |
case '.': | |
putchar(v[*i]); | |
break; | |
case '[': | |
fp = lseek(f, 0, SEEK_CUR) - 1; | |
if(v[*i] == 0) fuck(f); | |
else { | |
brain(f, v, i); | |
lseek(f, fp, SEEK_SET); | |
} | |
break; | |
case '0': | |
case ']': | |
return; | |
default: | |
break; | |
} | |
} | |
} | |
int main(int argc, char *argv[]) { | |
char v[BFSIZE]; | |
int f, i = 0; | |
if(argc != 2) { | |
printf("Usage: %s file\n", argv[0]); | |
return 1; | |
} | |
bzero(v, BFSIZE); | |
if((f = open(argv[1], O_RDONLY, 0)) < 0) { | |
perror("open"); | |
return 1; | |
} | |
brain (f, v, &i); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment