random

:-)
git clone read: git://git.margiolis.net/random.git
Log | Files | Refs | LICENSE

brainfuck.c (1219B)


      1 #include <stdio.h>
      2 #include <stdlib.h>
      3 #include <string.h>
      4 #include <unistd.h>
      5 
      6 #define BUFSIZE 50000
      7 
      8 int
      9 main(int argc, char *argv[])
     10 {
     11 	size_t len = 0;
     12 	int closed, opened, pos = 0;
     13 	unsigned short *pc;
     14 	char buf[BUFSIZE], *src;
     15 
     16 	while (read(STDIN_FILENO, &buf[len], 1) > 0)
     17 		len++;
     18 	buf[len] = '\0';
     19 
     20 	if ((src = malloc(len)) == NULL) {
     21 		perror("malloc");
     22 		exit(1);
     23 	}
     24 	strcpy(src, buf);
     25 	memset(buf, 0, len);
     26 
     27 	for (pc = (unsigned short *)buf; pos < len; pos++) {
     28 		switch (src[pos]) {
     29 		case '>':
     30 			pc++;
     31 			break;
     32 		case '<':
     33 			pc--;
     34 			break;
     35 		case '+':
     36 			(*pc)++;
     37 			break;
     38 		case '-':
     39 			(*pc)--;
     40 			break;
     41 		case '.':
     42 			putchar(*pc);
     43 			break;
     44 		case ',':
     45 			*pc = getchar();
     46 			break;
     47 		case '[':
     48 			if (!(*pc)) {
     49 				for (opened = 0, pos++; pos < len; pos++) {
     50 					if (src[pos] == ']' && !opened)
     51 						break;
     52 					else if (src[pos] == '[')
     53 						opened++;
     54 					else if (src[pos] == ']')
     55 						opened--;
     56 				}
     57 			}
     58 			break;
     59 		case ']':
     60 			if (*pc) {
     61 				for (closed = 0, pos--; pos >= 0; pos--) {
     62 					if (src[pos] == '[' && !closed)
     63 						break;
     64 					else if (src[pos] == ']')
     65 						closed++;
     66 					else if (src[pos] == '[')
     67 						closed--;
     68 				}
     69 			}
     70 			break;
     71 		}
     72 	}
     73 	free(src);
     74 
     75 	return 0;
     76 }