Originally Posted by
Rashakil Fol
Don't be silly mine is so poorly written it's embarressing.
I found an implementation written in 3 lines of C (well, several statements / expressions on each line). Mine is 112, including header comment I haven't included here.
Code:
#include "stdafx.h"
using namespace std;
int main(int argc, char *argv[])
{
FILE *f = 0;
char *programArray = 0;
char *ptr = 0;
char *ch = new char;
char line[60] = {0};
char *lnPtr = line;
char *commandBuf = new char[2048];
int arraySz = 0;
char *lback;
char *lford;
if (argc != 2)
{
cout << "Usage: b........ <filename>" << endl;
return -1;
}
f = fopen(argv[1], "r");
if (! f)
{
cout << "Error opening file " << argv[1] << endl;
return -1;
}
// attempt to get arraySz from first line
fgets(line, 60, f);
if (sscanf(line, "%d", &arraySz) != 1)
arraySz = 100; // default size
cout << "array size: " << arraySz << endl;
memset(line, 0, 60);
try
{
programArray = new char[arraySz];
}
catch (bad_alloc& e)
{
cout << "Error: " << e.what() << endl;
return -1;
}
for (int i = 0; i < arraySz; i++)
*(programArray + i) = 0;
// read whole program into commandBuf
ptr = commandBuf;
while ((*ch = fgetc(f)) != EOF)
*ptr++ = *ch;
ptr = &programArray[0];
ch = &commandBuf[0];
while (*ch != 'E')
{
switch (*ch)
{
case '>':
++ptr;
break;
case '<':
--ptr;
break;
case '+':
++*ptr;
break;
case '-':
--*ptr;
break;
case '.':
cout << *ptr;
break;
case ',':
cin >> *ptr;
break;
case '[':
lback = ch;
if (*ptr == 0)
{
while (*ch != ']')
++ch;
lford = ch;
ch = lback;
}
break;
case ']':
if (*ptr != 0)
{
ch = lback;
}
break;
}
ch++;
}
delete[] programArray;
delete[] commandBuf;
return 0;
}
Yeah it's fugly but it works. I've have no intention of updating it or anything since it was just written to waste an hour or so.
Slag it off if you feel the need, I'll just nod thoughtfully and go "I see".
(I probably will edit it, but you don't know that).