Advertisement
iocoder

bfcompiler

Nov 24th, 2014
247
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.65 KB | None | 0 0
  1. /* brainfuck compiler */
  2. /* By: Mostafa Abdelaziz */
  3. /* This software is FREE as in HELL */
  4.  
  5. #include <stdio.h>
  6. #include <unistd.h>
  7.  
  8. int main(int argc, char *argv[]) {
  9.  
  10.     FILE *src, *cfile;
  11.     char c;
  12.     char *gccvp[4];
  13.  
  14.     if (argc != 3)
  15.         return 0;
  16.  
  17.     if (!(src = fopen(argv[1], "r")))
  18.         return 0;
  19.  
  20.     if (!(cfile = fopen("/tmp/bftmp.c", "w"))) {
  21.         fclose(src);
  22.         return 0;
  23.     }
  24.  
  25.     fputs("#include <stdio.h>\n", cfile);
  26.     fputs("int main () {\n", cfile);
  27.     fputs("char array[4096] = {0};\n", cfile);
  28.     fputs("char *ptr = &array[2048];\n", cfile);
  29.  
  30.     while (fscanf(src, "%c", &c) != EOF) {
  31.  
  32.         switch (c) {
  33.             case '>':
  34.                 fputs("++ptr;\n", cfile);
  35.                 break;
  36.             case '<':
  37.                 fputs("--ptr;\n", cfile);
  38.                 break;
  39.             case '+':
  40.                 fputs("++*ptr;\n", cfile);
  41.                 break;
  42.             case '-':
  43.                 fputs("--*ptr;\n", cfile);
  44.                 break;
  45.             case '.':
  46.                 fputs("putchar(*ptr);\n", cfile);
  47.                 break;
  48.             case ',':
  49.                 fputs("*ptr=getchar();\n", cfile);
  50.                 break;
  51.             case '[':
  52.                 fputs("while (*ptr) {\n", cfile);
  53.                 break;
  54.             case ']':
  55.                 fputs("}\n", cfile);
  56.                 break;
  57.             default:
  58.                 break;
  59.         }
  60.  
  61.     }
  62.  
  63.     fputs("return 0;\n", cfile);
  64.     fputs("}\n", cfile);
  65.  
  66.     fclose(src);
  67.     fclose(cfile);
  68.  
  69.     execlp("gcc", "gcc", "-o", argv[2], "/tmp/bftmp.c", NULL);
  70.  
  71.     return 0;
  72.  
  73. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement