Advertisement
Evilerus

bfi

Mar 6th, 2017
102
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.79 KB | None | 0 0
  1. #include <iostream>
  2. #include <fstream>
  3. #include <string>
  4.  
  5. using namespace std;
  6.  
  7. void execCode(string progCode, unsigned char *p);
  8.  
  9. int main(int argc, char **argv)
  10. {
  11.     fstream Code;
  12.     string progCode = "", loadBuff;
  13.     unsigned char progMem[30000];
  14.     unsigned char *p;
  15.     int i;
  16.     if (argc==1)
  17.     {
  18.         cout << "usage: " << argv[0] << " filename.bf" << endl;
  19.         return 1;
  20.     }
  21.     else
  22.     {
  23.         Code.open(argv[1], ios::in);
  24.         if (Code.good() == true)
  25.         {
  26.             while (!Code.eof())
  27.             {
  28.                 getline(Code, loadBuff);
  29.                 progCode = progCode + loadBuff;
  30.                 loadBuff = "";
  31.             }
  32.             Code.close();
  33.         }
  34.         else
  35.         {
  36.             cout << "cannot open " << argv[1]  << endl;
  37.             return 2;
  38.         }
  39.         for (i=0; i<30000; i++)
  40.         {
  41.             progMem[i]=0;
  42.         }
  43.         p = &progMem[0];
  44.         execCode(progCode, p);
  45.     }
  46. }
  47.  
  48. void execCode(string progCode, unsigned char *p)
  49. {
  50.     unsigned int i = 0;
  51.     unsigned int loopCount = 0;
  52.     char currentInstruction;
  53.     for (i=0; progCode[i]!=0; i++)
  54.     {
  55.         currentInstruction=progCode[i];
  56.         switch(currentInstruction)
  57.         {
  58.             case '>':
  59.                 ++p;
  60.                 break;
  61.             case '<':
  62.                 --p;
  63.                 break;
  64.             case '+':
  65.                 ++(*p);
  66.                 break;
  67.             case '-':
  68.                 --(*p);
  69.                 break;
  70.             case '.':
  71.                 cout << *p;
  72.                 break;
  73.             case ',':
  74.                 cin >> *p;
  75.                 break;
  76.             case '[':
  77.                 continue;
  78.                 break;
  79.         }
  80.         if (currentInstruction == ']' && *p)
  81.         {
  82.             loopCount = 1;
  83.             while (loopCount > 0)
  84.             {
  85.                 currentInstruction = progCode[--i];
  86.                 if (currentInstruction == '[')
  87.                 {
  88.                     loopCount--;
  89.                 }
  90.                 else if (currentInstruction == ']')
  91.                 {
  92.                     loopCount++;
  93.                 }
  94.             }
  95.         }
  96.     }
  97. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement