输入:
brainfu*k 代码:
++++++++++[>+++++++>++++++++++>+++>+<<<<-]>++.>+.+++++++..+++.>++.<<+++++++++++++++.>.+++.------.--------.>+.>.
程序:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAXL 1000
/*
* brainfuck 转换为 c语言,并执行
* buffer[] 存储数据
* order[] 存储brainfuck命令
*/
int fun(char* brain_file)
{
FILE* input = fopen(brain_file, "r");
char buffer[MAXL] = {0};
char order[MAXL] = {0};
char *ptr, *wptr, *optr;
int wflag = 0;
optr = order;
ptr = buffer;
while (wflag || EOF != fscanf(input, "%c", optr))
{
//printf("%c", *optr);
switch(*optr)
{
case '>':
++ptr;
break;
case '<':
--ptr;
break;
case '+':
++*ptr;
break;
case '-':
--*ptr;
break;
case '.':
putchar(*ptr);
break;
case ',':
*ptr = getchar();
break;
case '[':
if (*ptr)
{
wptr = optr - 1;
}
else
{
wflag = 0;
}
break;
case ']':
wflag = 1;
optr = wptr;
break;
case '\n':break;
default:break;
}
optr++;
}
fclose(input);
return 0;
}
int main(int argc, char* argv[])
{
if(argc < 2)
{
printf("Usage: ./a.out brain_str");
return -1;
}
//printf("argv[1] is %s", argv[1]);
fun(argv[1]);
return 0;
}
运行结果:
Hello World!