Created
January 22, 2010 15:18
-
-
Save sirupsen/283826 to your computer and use it in GitHub Desktop.
Brainfuck parser in C using seeks.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdlib.h> | |
static char *ptr; | |
int do_command(const char command, FILE *pFile) | |
{ | |
char c; | |
int pos; | |
switch (command) | |
{ | |
case '>': | |
++ptr; // Move to next cell | |
break; | |
case '<': | |
--ptr; // Move to previous cell | |
break; | |
case '+': | |
++*ptr; // Increment cell | |
break; | |
case '-': | |
--*ptr; // Decrement cell | |
break; | |
case '.': | |
putchar(*ptr); // Print character | |
break; | |
case '[': | |
pos = ftell(pFile); // Get position of [ | |
// Perform the loop the times defined in the current cell | |
while (*ptr) | |
{ | |
fseek(pFile, pos, SEEK_SET); // Reset seek to the [ | |
c = getc(pFile); // Get the character | |
while (c != ']' && c != EOF) // While it's not end of the loop nor end of file | |
{ | |
do_command(c, pFile); // Execute commands | |
c = getc(pFile); // Get the next character | |
} | |
} | |
break; | |
} | |
} | |
int parse_source(const char *source) | |
{ | |
char command; // Stores each command | |
FILE *pFile = fopen(source, "r"); | |
if (pFile) // If we were able to open the file | |
{ | |
while ((command = getc(pFile)) != EOF) // For each character in file | |
{ | |
do_command(command, pFile); // Execute command | |
} | |
} | |
else | |
{ | |
puts("Not able to open file."); | |
} | |
fclose(pFile); | |
} | |
int main(int argc, const char *argv[]) | |
{ | |
int memory[9001]; // Make array to store values in | |
ptr = &memory; // Put it into the global pointer | |
parse_source(argv[1]); // Parse the source file defined in argument | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment