Advertisement
theelitenoob

Brainf*** Interpter

Jul 21st, 2012
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.98 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4.  
  5. unsigned char tape[30000] = {0}; // Set the tape equal to zero, bf only calls for 30000 bytes available in the tape
  6. unsigned char* ptr = tape; // The pointer to the tape, this is what we work with!
  7.  
  8. int main(int argc, char *argv[]){
  9.     // The file handling section
  10.  
  11.     // Make sure there is an argument to the interpter
  12.     if(argc < 2){
  13.         printf("\nCorrect usage is: bfi <source.txt>\n");
  14.         exit(8); // Exit program
  15.     }
  16.     // Read in the input from a text based file
  17.     FILE *file;
  18.     file = fopen(argv[1], "r"); // Read the file to file...
  19.     int p, size;
  20.     p = size = 0; // Set stuff equal to zero
  21.     char c; // Current char beind read
  22.     // Read stuff into the char array.
  23.     if(file == NULL){
  24.         printf("\nFile could not be opened!\n");
  25.         exit(8); // Exit the program
  26.     }
  27.     // make char input array size of required input
  28.     fseek(file, 0, SEEK_END);
  29.     size = ftell(file);
  30.     fseek(file, 0, SEEK_SET);
  31.     char input[size]; // Set up the input for proper size
  32.     while((c=fgetc(file)) != EOF)
  33.         input[p++] = (char) c; // Read in the file
  34.     fclose(file); // Close the file, we have the input array
  35.  
  36.     // The interpter section
  37.     int i, loop; // Iterator and loop counter
  38.     for(i = 0; input[i] != 0; i++){ // Go through 1 command at a time
  39.         c = input[i]; // get current char
  40.         // Interpet the commands according to wikipedia's article
  41.         if(c == '+')
  42.             ++*ptr;
  43.         else if(c == '-')
  44.             --*ptr;
  45.         else if(c == '>')
  46.             ++ptr;
  47.         else if(c == '<')
  48.             --ptr;
  49.         else if(c == ',') // get input
  50.             *ptr = getchar();
  51.         else if(c == '.') // print current char
  52.             putchar(*ptr);
  53.         else if(c == '[') // skip over this, go to ] section
  54.             continue;
  55.         else if(c == ']' && *ptr){ // make sure there is something in *ptr
  56.             loop = 1; // We are in a loop!
  57.             while(0 < loop){ // While we are still in a loop
  58.                 c = input [--i]; // Get c
  59.                 if(c == '[')
  60.                     loop--; // No more loop!
  61.                 else if(c == ']')
  62.                     loop++; // Another loop!
  63.             }
  64.         }
  65.     }
  66.     return 0;
  67. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement