Ckef01

Simple Fast Brainfuck Interpreter

Feb 28th, 2013
126
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.39 KB | None | 0 0
  1. #include <stdio.h>
  2.  
  3. #define SIZE 30000
  4. #define INDEX (SIZE - 1)
  5.  
  6. int main(int argc, char *argv[])
  7. {
  8.     if(argc < 2) return 1; // Need a file!
  9.     FILE *file = fopen(argv[1], "r");
  10.     if(!file) return 1;
  11.  
  12.     char array[SIZE];
  13.     char *ptr = array;
  14.     long int depth = 0;
  15.  
  16.     while(!feof(file))
  17.     {
  18.         char curr = fgetc(file);
  19.         long int currDepth = depth;
  20.         switch(curr)
  21.         {
  22.             case '>' : ptr = ptr == array + INDEX ? array : ptr + 1; break;
  23.             case '<' : ptr = ptr == array ? array + INDEX : ptr - 1; break;
  24.             case '+' : ++(*ptr); break;
  25.             case '-' : --(*ptr); break;
  26.             case '.' : putchar(*ptr); break;
  27.             case ',' : while((*ptr = getchar()) == '\n'); break;
  28.             case '[' : ++depth; if(!*ptr) while(depth > currDepth) switch(curr = fgetc(file))
  29.             {
  30.                 case '[' : ++depth; break;
  31.                 case ']' : --depth; break;
  32.             }
  33.             break;
  34.             case ']' : --depth; if(*ptr) while(depth < currDepth)
  35.             {
  36.                 fseek(file, -2, SEEK_CUR);
  37.                 switch(curr = fgetc(file))
  38.                 {
  39.                     case '[' : ++depth; break;
  40.                     case ']' : --depth; break;
  41.                 }
  42.             }
  43.             break;
  44.         }
  45.     }
  46.  
  47.     fclose(file);
  48.     putchar('\n');
  49.     return 0;
  50. }
Advertisement
Add Comment
Please, Sign In to add comment