Advertisement
theelitenoob

Brainf*** Compiler

Jul 21st, 2012
66
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.92 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4.  
  5. int main(int argc, char *argv[]){
  6.     // The file handling section
  7.     // Make sure there is an argument to the interpter
  8.     if(argc < 2){
  9.         printf("\nCorrect usage is: bfc <source.txt>\n");
  10.         exit(8); // Exit program
  11.     }
  12.     // Read in the input from a text based file
  13.     FILE *file;
  14.     file = fopen(argv[1], "r"); // Read the file to file...
  15.     int p, size;
  16.     p = size = 0; // Set stuff equal to zero
  17.     char c; // Current char beind read
  18.     // Read stuff into the char array.
  19.     if(file == NULL){
  20.         printf("\nFile could not be opened!\n");
  21.         exit(8); // Exit the program
  22.     }
  23.     // make char input array size of required input
  24.     fseek(file, 0, SEEK_END);
  25.     size = ftell(file);
  26.     fseek(file, 0, SEEK_SET);
  27.     char input[size]; // Set up the input for proper size
  28.     while((c=fgetc(file)) != EOF)
  29.         input[p++] = (char) c; // Read in the file
  30.     fclose(file); // Close the file, we have the input array
  31.     // The writing section
  32.     int i; // Iterator
  33.     FILE *cfile; // output file
  34.     cfile = fopen("temp.c", "a+");
  35.     fprintf(cfile, "#include <stdio.h>\n\n");
  36.     fprintf(cfile, "char tape[30000];\nchar *ptr = tape;\n");
  37.     fprintf(cfile, "\nint main(){\n");
  38.     for(i = 0; input[i] != 0; i++){ // Go through 1 command at a time
  39.         c = input[i]; // get ")rrent char
  40.         if(c == '+')
  41.             fprintf(cfile, "\t++*ptr;\n");
  42.         else if(c == '-')
  43.             fprintf(cfile, "\t--*ptr;\n");
  44.         else if(c == '>')
  45.             fprintf(cfile, "\t++ptr;\n");
  46.         else if(c == '<')
  47.             fprintf(cfile, "\t--ptr;\n");
  48.         else if(c == ',') // get input
  49.             fprintf(cfile, "\t*ptr = getchar();\n");
  50.         else if(c == '.') // print current char
  51.             fprintf(cfile, "\tputchar(*ptr);\n");
  52.         else if(c == '[')
  53.             fprintf(cfile, "\twhile(*ptr){\n");
  54.         else if(c == ']'){
  55.             fprintf(cfile, "\t}\n");
  56.             }
  57.         }
  58.         fprintf(cfile, "\treturn 0;\n}\n");
  59.         fclose(cfile); // close out the file
  60.         system("gcc -Wall -o out temp.c");
  61.         system("del temp.c");
  62.         return 0;
  63. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement