Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- unsigned char cells[30000] = {0}; //the tape
- FILE *inFile = NULL; //file to read brainfuck from
- int fileSize = 0; //length of file text
- int position = 0; //where i am on the tape
- int loopcount = 0; //how far i am nested in a loop
- int counter;
- char *bf; //string containing brainfuck to be interpretted
- int main()
- {
- inFile = fopen("test.bf", "r");
- while(fgetc(inFile) != EOF)
- {
- fileSize++;
- }
- rewind(inFile);
- bf = (char *)malloc(sizeof(char) * (fileSize + 1 + 1)); // one for space one for null
- for(counter = 0; counter < fileSize; counter++)
- {
- *(bf + counter) = fgetc(inFile);
- }
- printf("\n%s", bf); //print the .bf source code
- if (inFile)
- {
- for (counter = 0; counter < fileSize; counter++)
- switch(bf[counter])
- {
- case '+':
- cells[position]++;
- break;
- case '-':
- cells[position]--;
- break;
- case '>':
- position++;
- if (position > 30000)
- {
- position = 0;
- }
- break;
- case '<':
- position--;
- if (position < 0)
- {
- position = 30000;
- }
- break;
- case '[':
- if(!cells[position])
- {
- loopcount++;
- while(loopcount)
- {
- loopcount++;
- if(bf[counter] == ']')
- {
- loopcount--;
- }
- else if(bf[counter] == '[')
- {
- loopcount++;
- }
- }
- }
- break;
- case ']':
- if(cells[position])
- {
- loopcount++;
- while(loopcount)
- {
- counter--;
- if(bf[counter] == '[')
- {
- loopcount--;
- }
- else if(bf[counter] == ']')
- {
- loopcount++;
- }
- }
- }
- break;
- case '.': // output pointer value
- putchar(cells[position]);
- break;
- case ',': // read in value
- cells[position] = getchar();
- break;
- }
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement