Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #define BUF_SIZE 30000
- #define CODE_SIZE 4096
- #include <stdio.h>
- #include <stdlib.h>
- struct linked_list
- {
- int index;
- struct linked_list *next;
- };
- struct linked_list *stack_add(struct linked_list *list, int data)
- {
- struct linked_list *ptr = malloc(sizeof(struct linked_list));
- ptr->next = list;
- ptr->index = data;
- return ptr;
- }
- struct linked_list *stack_remove(struct linked_list *list)
- {
- struct linked_list *ptr = list->next;
- free(list);
- return ptr;
- }
- int interpret(char *code, unsigned char *buf, int index)
- {
- struct linked_list *brackets = NULL;
- int c_index = 0;
- while(code[c_index])
- {
- //printf("c_index = %d\tcode = %c\tindex = %d\tbuf = %d\n",c_index,code[c_index],index,buf[index]);
- switch(code[c_index++])
- {
- case '>':
- index++;
- break;
- case '<':
- index--;
- break;
- case '+':
- buf[index]++;
- break;
- case '-':
- buf[index]--;
- break;
- case '.':
- putchar(buf[index]);
- break;
- case ',':
- buf[index] = getchar();
- break;
- case '[':
- if(!buf[index])
- {
- while(code[c_index++]!=']');
- if((brackets!=NULL) && (brackets->index == index))
- brackets = stack_remove(brackets);
- }
- else
- if((brackets==NULL) || (brackets->index != index))
- brackets = stack_add(brackets, index);
- break;
- case ']':
- while(code[--c_index]!='[');
- break;
- }
- }
- return index;
- }
- void execute(char *code)
- {
- unsigned char buf[BUF_SIZE] = {0};
- interpret(code, buf, 0);
- }
- int main(int argc, char **argv)
- {
- if(argc>1)
- {
- int size;
- FILE *file = fopen(argv[1], "r");
- char *code;
- if(file == NULL)
- {
- printf("Error, could not open file (%s)\n", argv[1]);
- return 0;
- }
- fseek(file, 0, SEEK_END);
- size = ftell(file);
- rewind(file);
- code = malloc(size);
- fread(code, size, 1, file);
- printf("loaded program: (%d bytes)\n%s\nStarting...\n", size, code);
- execute(code);
- return 0;
- }
- else
- {
- unsigned char buffer[BUF_SIZE] = {0};
- char code[CODE_SIZE];
- int buf_index = 0;
- printf("Brainfuck Interpreter Shell\n");
- while(1)
- {
- char open_loop = 0;
- int index = 0;
- printf("\n>> ");
- do
- {
- fgets(&code[index], CODE_SIZE, stdin);
- for(;code[index]!=0;index++)
- if(code[index]=='[')
- open_loop++;
- else
- if(code[index]==']')
- open_loop--;
- if(open_loop)
- printf(">>\t");
- } while(open_loop | !index);
- buf_index = interpret(code, buffer, buf_index);
- }
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement