/* bfc.c - Don Yang (uguu.org) Simple BF to C compiler. 09/06/04 */ #include #include #define BUFSIZE 0x10000 #define MAX_TAPE_SIZE 0x10000 int main(int argc, char **argv) { static char buffer[BUFSIZE], *p; FILE *infile, *outfile; size_t s; int n; if( argc > 1 ) { if( (infile = fopen(argv[1], "rb")) == NULL ) return printf("Can not open %s\n", argv[1]); if( argc > 2 ) { if( (outfile = fopen(argv[2], "wb+")) == NULL ) { (void)fclose(infile); return printf("Can not create %s\n", argv[2]); } } else { outfile = stdout; } } else { infile = stdin; outfile = stdout; } n = 0; (void)fprintf(outfile, "#include\n" "#include\n" "static int Tape[%d];\n" "int main(void)\n{\n" "int *x=&Tape[0];\n" "memset(x,0,%d*sizeof(int));\n", MAX_TAPE_SIZE, MAX_TAPE_SIZE); while( (s = fread(buffer, 1, BUFSIZE, infile)) > 0 ) { for(p = buffer; s-- > 0; p++) { switch( *p ) { case '[': (void)fputs("\nwhile(*x){\n", outfile); n++; break; case ']': (void)fputs("\n}\n", outfile); n--; break; case '<': (void)fputs("--x;", outfile); break; case '>': (void)fputs("++x;", outfile); break; case '-': (void)fputs("--*x;", outfile); break; case '+': (void)fputs("++*x;", outfile); break; case ',': (void)fputs("\n*x=getchar();", outfile); break; case '.': (void)fputs("putchar(*x);\n", outfile); break; default: break; } } if( n < 0 ) n = -2; } (void)fputs("\nreturn 0;\n}\n", outfile); if( n != 0 ) (void)fputs("[] unbalanced\n", stderr); (void)fclose(infile); (void)fclose(outfile); return 0; }