Skip to content

Instantly share code, notes, and snippets.

@federicobond
Created October 9, 2011 04:34
Show Gist options
  • Save federicobond/1273302 to your computer and use it in GitHub Desktop.
Save federicobond/1273302 to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#define MEM_SIZE 30000
#define BUF_SIZE 2000
void execute(const char prg[]);
int read_file(FILE *f, char buf[], const int bufsize);
int
main(int argc, const char *argv[])
{
int i;
FILE *f ;
char buf[BUF_SIZE];
if (argc == 1) {
printf("No input files.\n");
return 1;
}
for (i = 1; i < argc; i++) {
f = fopen(argv[i], "r");
if (f == NULL) {
printf("Invalid input file %d\n", i);
return 1;
}
if (read_file(f, buf, BUF_SIZE)) {
execute(buf);
}
fclose(f);
}
return 0;
}
int read_file(FILE *f, char buf[], const int buf_size) {
int idx = 0;
char c;
while (idx < buf_size && (c = getc(f)) != EOF) {
/* Ignore whitespace */
if (isspace(c)) {
continue;
}
/* Error on invalid tokens */
if (c != '+' && c != '-' && c != '>' && c != '<' && c != '.'
&& c != ',' && c != '[' && c != ']')
{
printf("Invalid token found in file: '%c'.\n", c);
return 0;
}
buf[idx++] = c;
}
buf[idx] = '\0';
return 1;
}
void
execute(const char prg[])
{
long t = 0;
unsigned char mem[MEM_SIZE] = {0};
int p = MEM_SIZE/2;
int pc = 0;
while (prg[pc] != '\0') {
t++;
switch (prg[pc]) {
case '>':
p++;
break;
case '<':
p--;
break;
case '+':
mem[p]++;
break;
case '-':
mem[p]--;
break;
case '.':
putchar(mem[p]);
break;
case ',':
mem[p] = getchar();
break;
case ']':
if (mem[p] != 0) {
while (prg[pc] != '[')
pc--;
}
break;
case '[':
if (mem[p] == 0) {
while (prg[pc] != ']')
pc++;
}
break;
}
if (prg[pc] != '\0') {
pc++;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment