star

搜索

RSS

RSS Link

计数器

140160

BrainFuck解释器

2011年2月01日 08:57 | Comments(19) | Category:C语言 | Tags:

无注释版本:

#include <stdio.h>
#include <stdlib.h>

#define SIZE 5000

char data[SIZE], code[SIZE]; 
int  ptr, flag;

void interpreter(char *ip)
{
	char* re;
	
	while (*ip)
	{
		switch(*ip++)
		{
			case '<': --ptr;  break;
			case '>': ++ptr;  break;
			case '+': ++data[ptr]; break;
			case '-': --data[ptr]; break;
			case '.': putchar(data[ptr]);    fflush(stdout); break;
			case ',': data[ptr] = getchar(); fflush(stdout); break;
			case '[': for (flag=1,re=ip; flag && *ip; ++ip)
							flag += *ip=='[', flag -= *ip==']';
				  	  if(!flag)
				  	  {
				  	  		ip[-1] = 0;
				  	  		while (data[ptr])
				  	  			interpreter(re);
			  	  			ip[-1] = ']';
			  	  			break;
				  	  }
			case ']': puts("Unbalancded brackets!"), exit(-3);
			default : ;//SKIP
		}
		if (ptr < 0 || ptr > 100)
			puts("Out of Range"), exit(-4);
	}
}
 
int main(int argc, char *argv[])
{
	FILE *fin;
	int codelength;
	
	if (argc != 2)
		return puts("BrainFuck Interpreter v 0.1\nStar\nUsage:BFI filename"), 0;
	if ((fin = fopen(argv[1], "r")) == NULL)
		return puts("Cannot open file!"), -1;
	fseek(fin, 0, SEEK_END);
	if ((codelength = ftell(fin)) > SIZE)
		return puts("The program is too large."), -2;
	fseek(fin, 0, SEEK_SET);
	fread(code, codelength, 1, fin);
	code[codelength] = '\0';
	interpreter(code);
	return 0;
}