Exemple #1
0
int main(int argc, char * argv[]) {

   if(argc==1)
   {
      printf("Debe Ingresar el Nombre del Archivo\n");
      return -1;
   }
   if(argc!=2)
   {
      printf("Nombre Incorrecto de Argumento\n");
      return -2;
   }
   if((in = fopen(argv[1],"r"))==NULL)
   {
      printf("No se puede Abrir el Archivo\n");
      return -3;
   }


   TOKEN a;

   while (((a=Scanner())!=13))
   {
      ImprimeToken(a);
      if(a==-4)
      {
         printf("ERROR LEXICO");
         break;
      }
   }

   fclose(in);
}
Exemple #2
0
bool            ScanEOL( void ) {
//=========================

// Check for end-of-line.

    return( *Scanner() == NULLCHAR );
}
Exemple #3
0
Scanner::Scanner(const string& filename){
	//inspect the file is readable
	std::ifstream* file;
	file = new std::ifstream(filename.c_str());
	//read everything in oreturn NUMERIC;ur buffer
	if(file && file->is_open()){
		string* str = new string("");

		char c; int ch;

		while(true){
			c = ch = file->get();
			if(ch!=-1)
				str->append(1, c);
			else
				break;
		}

		Scanner(str->data());
		file->close();
	}else{
		string err(""); err.append(ERROR_MSG[3]).append(filename);
		//report
		throw new YottaError(FILE_ERROR, err, line, 0);
	}

	//TODO : consider in case we've open the file before
	delete file;
}
Exemple #4
0
int main() {
	string input;
	while (prompt(input)) {
		istringstream iss(input);
		try {
			cout << "      = " << flush;
			Lexer Lexer(iss);
			Scanner Scanner(Lexer);
			cout << *(Scanner.Scan()->Evaluate(BuiltInEnvironment())) << endl;
		} catch (InternalError const &re) {
			cerr << "internal error" << endl;
		} catch (SyntaxError const &re) {
			cerr << "syntax error" << endl;
		} catch (PreprocessError const &re) {
			cerr << "preprocess error" << endl;
		} catch (RuntimeError const &re) {
			cerr << "runtime error" << endl;
		} catch (UserException const &re) {
			cerr << "exception: " << *(re.m_pValue) << endl;
		} catch (ExitException const &re) {
			return re.m_pCode->m_n;
		}
	}
	cout << endl;
}
Exemple #5
0
int main(int argc,char *argv[]){
	Map Board;
	char *intro[] = {"○ : 사용자","● : 컴퓨터","방향키 : 이동","스페이스바 : 돌 놓기"};
	int _x,_y,position,i,j;
	system("mode con:cols=60 lines=20");
	system("cls");
	Map_set(&Board);
	for(i=0;i<4;i++){
		gotoxy(40,i);
		printf("%s",intro[i]);
	}
	_x = 16;
	_y = 8;
	gotoxy(_x,_y);
	while(1){
		if(User_mv(&_x,&_y,&Board)){
			Board.arrBoard[_y][_x/2] = USER;
			Board.arrDanger[_y][_x/2] = -1;
			Board.arrFavor[_y][_x/2] = -1;
			Scanner(_y,_x/2,&Board);
			Com_Turn(&Board);

		}

	}
	return 0;
}
Exemple #6
0
int main (int argc, char *argv[]) {
	if (argc != 2) {
		printf("usage: ./tokenize tm_file\n");
		exit(1);
	} else if (argc == 2) {
		FILE *fp;
		fp = fopen ( argv[1], "r");
		if ( fp == NULL ) {
			// something went wrong
			perror( argv[1] );
			exit( 1 );
		}
		// build matrix
		TransMatrix transMatrix = BuildMatrix(fp);
		// print matrix
		displayMatrix(transMatrix);
		/* process stdin and print state transitions from start
		to accepting state until end of file	
		*/
		while(Scanner(transMatrix) != EOF);
		//Scanner(transMatrix);
		// close the stream
		fclose(fp);
		}
	return 0;
}
Exemple #7
0
bool            ScanChar( char chr ) {
//====================================

// Scan a character.

    if( *Scanner() == chr ) {
        IOCB->fileinfo->col++;
        return( TRUE );
    }
    return( FALSE );
}
Exemple #8
0
int main( int /* argc */, char** /* argv */ )
{
	Scanner scanner = Scanner();
	
	SymbolTable st = SymbolTable();
	
	Token *currTok;
	currTok = scanner.nextToken();
	
	while( 1 )
	{					
		std::cout << currTok->tokenCodeToString();
		
		if( currTok->getDataType() == dt_OP )
			std::cout << "(" << currTok->opCodeToString() << ")";
		else if( currTok->getDataType() != dt_KEYWORD && currTok->getDataType() != dt_NONE )
		{
			std::cout << "(" << currTok->getDataValue().lexeme << ")";
		}	
		std::cout << " ";
		
		
		//symtab
		if( currTok->getTokenCode() == tc_ID || currTok->getTokenCode() == tc_NUMBER )
		{
			SymbolTableEntry *entry = st.lookup( currTok->getDataValue().lexeme );
			
			if(!entry)
			{
				entry = st.insert( currTok->getDataValue().lexeme );
				currTok->setSymTabEntry( entry );
			}
			currTok->setSymTabEntry( entry );	
		}
		
		
		if(currTok->getTokenCode() == tc_EOF)
			break;
		currTok = scanner.nextToken();
	}
	
	std::cout << "\n\n";
	st.print();
	return 0;
}
Exemple #9
0
char            *ScanName( uint *len ) {
//======================================

// Scan a name.

    char        *name;
    char        *ptr;
    char        chr;

    name = Scanner();
    for( ptr = name; ; ++ptr ) {
        chr = *ptr;
        if( isalnum( chr ) ) continue;
        if( chr == '_' ) continue;
        if( chr == '$' ) continue;
        break;
    }
    *len = ptr - name;
    IOCB->fileinfo->col += *len;
    return( name );
}
Exemple #10
0
bool            ScanSNum( signed_32 PGM *num ) {
//==============================================

// Scan a signed number.

    char        *ptr;

    Blanks();
    ptr = Scanner();
    if( ( *ptr == '+' ) || ( *ptr == '-' ) ) {
        ++ptr;
    }
    if( isdigit( *ptr ) ) {
        *num = GetNum();
        Blanks();
        return( TRUE );
    } else {
        Blanks();
        return( FALSE );
    }
}
int main(int argc, char* argv[])
{
	std::cout << "Enter main." << std::endl;
	
	std::string InputFile, OutputFile;
	double ScannerLocX, ScannerLocY, ScannerLocZ;
	double ForwardX, ForwardY, ForwardZ;
	unsigned int NumPoints;
	double ThetaMin, ThetaMax, PhiMin, PhiMax, minmax;

	std::cout << "Options:" << std::endl;
	
	po::options_description desc("Allowed options");
	desc.add_options()
			("help", "Help message.")
			("input", po::value<std::string>(&InputFile), "Set input file")
			("output", po::value<std::string>(&OutputFile), "Set output file")
			("ScannerLocX", po::value<double>(&ScannerLocX)->default_value(0.0), "Set scanner location (x)")
			("ScannerLocY", po::value<double>(&ScannerLocY)->default_value(0.0), "Set scanner location (y)")
			("ScannerLocZ", po::value<double>(&ScannerLocZ)->default_value(0.0), "Set scanner location (z)")
			("ForwardX", po::value<double>(&ForwardX)->default_value(0.0), "Set forward (x)")
			("ForwardY", po::value<double>(&ForwardY)->default_value(0.0), "Set forward (y)")
			("ForwardZ", po::value<double>(&ForwardZ)->default_value(0.0), "Set forward (z)")
			("NumPoints", po::value<unsigned int>(&NumPoints)->default_value(100), "Set number of points (one side of the grid, assuming a square grid)")
			("PhiMin", po::value<double>(&PhiMin)->default_value(-10.0), "Set min phi angle")
			("PhiMax", po::value<double>(&PhiMax)->default_value(10.0), "Set max phi angle")
			("ThetaMin", po::value<double>(&ThetaMin)->default_value(-10.0), "Set min theta angle")
			("ThetaMax", po::value<double>(&ThetaMax)->default_value(10.0), "Set max theta angle")
			("minmax", po::value<double>(&minmax), "Set max theta angle")
			;

	po::variables_map vm;
	po::store(po::parse_command_line(argc, argv, desc), vm);
	po::notify(vm); //assign the variables (if they were specified)
	
	if(vm.count("help")) 
	{
		std::cout << desc << std::endl;
		return 1;
	}

	CheckRequiredArgs(vm);
	
	std::cout << std::endl << std::endl;

	if(!vm.count("minmax"))
	{
		//convert degrees to radians
		PhiMin = deg2rad(PhiMin);
		PhiMax = deg2rad(PhiMax);
		ThetaMin = deg2rad(ThetaMin);
		ThetaMax = deg2rad(ThetaMax);
	}
	else
	{
		PhiMin = deg2rad(-minmax);
		PhiMax = deg2rad(minmax);
		ThetaMin = deg2rad(-minmax);
		ThetaMax = deg2rad(minmax);
	}
	/////////////////////////////////////////////////////
	
	//setup model
	ModelFile Scene;
	Scene.Read(InputFile);
	Scene.Init();
	
	//setup scanner
	LidarScanner Scanner(true); //use octree
	Scene.BuildOctree();
	vgl_point_3d<double> Pos(ScannerLocX, ScannerLocY, ScannerLocZ);
	vgl_vector_3d<double> Dir(ForwardX, ForwardY, ForwardZ);
	Scanner.Orient(Pos, Dir);	

	Scanner.ScanParams.setNumPhiPoints(NumPoints);
	Scanner.ScanParams.setNumThetaPoints(NumPoints);
	
	Scanner.ScanParams.setPhiMin(PhiMin);
	Scanner.ScanParams.setPhiMax(PhiMax);
	Scanner.ScanParams.setThetaMin(ThetaMin);
	Scanner.ScanParams.setThetaMax(ThetaMax);
	
	//scan
	PerformScan(Scene, Scanner, OutputFile);
	return 0;

}
Exemple #12
0
void main()
{
	srand(time(NULL));
	
	// dynamic memory allocation
	// creates an array of instances of the Cell class with a dynamic size.
	// this is setup in a way so that you could ask the user for an array size and it would allocate the required amout of memory.
	Cell* cell;
	cell = new Cell[16];

	// calls the function that creates the grid to be used as the game map defined as a 4 x 4 grid stored inside the dynamic cell array.
	createGrid(4, cell);

	// creates a varible to be used as a text file.
	fstream gameSave;

	// makes a bool variable used to define the default win condition as false until changed when certain criteria is met.
	bool winCondition = false;

	// creates an instance of the Player class named player defined as the constructor function.
	Player player = Player();

	// creates an instance of the Scanner class name scanner defined as the constructor function.
	Scanner scanner = Scanner();

	// creates an instance of the Gold class named gold defined as the constructor function.
	Gold gold = Gold();

	// creates an instance of the Wumpus class named wumpus defined as the constructor function.
	Wumpus wumpus = Wumpus({ RNG(4),RNG(4) });

	cout << "Wumpus location: " << wumpus.location.x << " = x, " << wumpus.location.y << " = y" << endl;
	cout << "\n";

	// creates an array of instances of the Pit class.
	Pit pits[4] = { Pit({1,1}), Pit({ 1,3 }), Pit({ 3,0 }), Pit({ 3,3 }) };

	// creates an instance of the Arrow class name arrow defined as the constructor function.
	Arrow arrow = Arrow();

	// displays instructions for the user to the console.
	cout << "Type your input then press enter to do actions" << endl;
	cout << "Use 'w','a','s','d' as the arrow keys to move." << endl;
	cout << "Use 'f' to draw your bow then 'w','a','s','d' to shoot in a direction ." << endl;
	cout << "Use 'r' to check your scanner." << endl;
	cout << "Use 'q' to save, and 'e' to load a save" << endl;
	cout << "\n";
		
	cout << "You enter the cave of the Wumpus monsters in search of gold..." << endl;
	cout << "\n";
	
	cout << "Which direction do you want to go?" << endl;
	cout << "\n";

	// starts the game loop.
	do
	{
		// makes a char variable used to store user input to be used in the movement switch case statements.
		char input;

		// takes in the users input to be check against the switch/case statments.
		cin >> input;
		cout << "\n";

		// tells the user that the wrong input was entered and lists the correct inputs if the wrong input was entered.
		if (!(input == 'w' || input == 'a' || input == 's' || input == 'd' || input == 'q' || input == 'e' || input == 'f' || input == 'r'))
		{
			cout << "That is not a valid input..." << endl;
			cout << "Use 'w','a','s','d' as the arrow keys to move." << endl;
			cout << "Use 'f' to draw your bow then 'w','a','s','d' to shoot in a direction ." << endl;
			cout << "Use 'r' to check your scanner, you only have 2." << endl;
			cout << "Use 'q' to save, and 'e' to load a save." << endl;
			cout << "\n";
		}

		// creates a switch/case statment thats accepts the character variable "input".
		switch (input)
		{
			// adds 1 to the players "y" cooridinate if 'w' was the input.
		case 'w':
			player.location.x, player.location.y += 1;
			cout << "You moved to the North..." << endl;
			cout << "Your X, Y position is: " << player.location.x << ", " << player.location.y << endl;
			cout << "\n";
				break;

			// subtracts 1 from the players "y" cooridinate if 's' was the input.
		case 's':
			player.location.x, player.location.y -= 1;
			cout << "You moved to the South..." << endl;
			cout << "Your X, Y position is: " << player.location.x << ", " << player.location.y << endl;
			cout << "\n";
				break;

			// subtracts 1 to the players "x" cooridinate if 'a' was the input.
		case 'a':
			player.location.x -= 1, player.location.y;
			cout << "You moved to the West..." << endl;
			cout << "Your X, Y position is: " << player.location.x << ", " << player.location.y << endl;
			cout << "\n";
				break;

			// adds 1 to the players "x" cooridinate if 'd' was the input.
		case 'd':
			player.location.x += 1, player.location.y;
			cout << "You moved to the East..." << endl;
			cout << "Your X, Y position is: " << player.location.x << ", " << player.location.y << endl;
			cout << "\n";
				break;

			// calls the useScanner function to scan the area if 'r' was the input.
		case 'r':
			scanner.useScanner(scanner, player, pits, wumpus, gold);
			scanner.charge -= 1;
			break;

			// calls the shootArrow function to shoot an arrow in the direction of the user input.
		case 'f':
			if (arrow.shootArrow(arrow, player, wumpus) == true)
			{
				wumpus.alive = false;
				cout << "You have killed the Wumpus monster!" << endl;
				cout << "\n";
			}

			else
			{
				cout << "You didnt hit anything..." << endl;
				cout << "\n";
			}
				break;

			// saves the players data to a file if 'q' was the input.
		case 'q':

			gameSave.open("gameSave.txt", ios_base::out);
	
			gameSave << player.location.x << "\n" <<  player.location.y << "\n" << player.gold << "\n" << wumpus.alive;

			gameSave.close();
				
			cout << "Game has been saved." << endl;
			cout << "\n";
				break;

			// loads the players data from a file if 'e' was the input.
		case 'e':
		
			gameSave.open("gameSave.txt", ios_base::in);
				
			gameSave >> player.location.x >> player.location.y >> player.gold >> wumpus.alive;
			
			gameSave.close();
				
			cout << "Game has been loaded." << endl;
			cout << "\n";
			cout << "Your X, Y position is: " << player.location.x << ", " << player.location.y << endl;
			cout << "\n";
				break;
			
		default:
				break;
		}
	
		if ((player.location.x == pits[0].location.x) && (player.location.y == pits[0].location.y))
		{
			player.alive = false;
			cout << "You fall in a giant pit and are trapped forever..." << endl;
			cout << "\n";
		}

		if ((player.location.x == pits[1].location.x) && (player.location.y == pits[1].location.y))
		{
			player.alive = false;
			cout << "You fall in a giant pit and are trapped forever..." << endl;
			cout << "\n";
		}

		if ((player.location.x == pits[2].location.x) && (player.location.y == pits[2].location.y))
		{
			player.alive = false;
			cout << "You fall in a giant pit and are trapped forever..." << endl;
			cout << "\n";
		}

		if ((player.location.x == pits[3].location.x) && (player.location.y == pits[3].location.y))
		{
			player.alive = false;
			cout << "You fall in a giant pit and are trapped forever..." << endl;
			cout << "\n";
		}

		// displays a message to the console that you have died if the Player's "x" or "y" coordinate is not on the game map grid it sets the Alive bool of the Player to false.
		if ((player.location.x == -1) ||
		(player.location.x == 4) ||
		(player.location.y == -1) ||
		(player.location.y == 4))
		{
			player.alive = false;
			cout << "You fall of a ledge to your death..." << endl;
			cout << "\n";
		}

		// displays a message to the console that you have died if the players "x" and "y" coordinates are equal to that of the Wumpus it sets the alive bool of the Player to false.
		if ((player.location.x == wumpus.location.x) && (player.location.y == wumpus.location.y) && (wumpus.alive == true))
		{
			player.alive = false;
			cout << "A Wumpus monster bites your head off.." << endl;
			cout << "\n";
		}

		// if the Player's "x" and "y" coordinates are equal to that of the Gold it sets the Gold bool of the Player to true.
		// dislplays a message to the colse to tell the play that they have picked up the gold and must leave the cave.
		if ((player.location.x == gold.location.x) && (player.location.y == gold.location.y) && (gold.onGround == true))
		{
			player.gold = true;
			gold.onGround = false;
			cout << "You have found the gold, now you must escape the Wumpus cave" << endl;
			cout << "\n";
		}

		// if the players alive bool is false it sets the winCondition bool to false.
		if (player.alive == false)
		{
			winCondition = false;
		}
			
		// if the players "x" and "y" coordinates are equal to the start position (0,0) and the gold bool is true it sets the winCondition to true.
		if ((player.gold == true) && (player.location.x == 0) && (player.location.y == 0))
		{
			winCondition = true;
		}

		// while the winCondition bool is false and the players alive bool is true continue to execute this loop.
	} while ((winCondition == false) && (player.alive == true));
	
	//if the winCondtion bool is true and the players alive bool is true display to the console that they have won the game.
	if ((winCondition == true) && (player.alive == true))
	{
		cout << "\n";
		cout << "\n";
		cout << "Congradulations you escaped the cave with the gold!" << endl;
		cout << "\n";
		
		// clears the save game file if the winCondition bool is true.
		gameSave.open("gameSave.txt", ios_base::out);
		
		gameSave.close();
	}
	
	// deallocates the dynamic memory of the Cell array.
	delete[] cell;

	system("pause");
}
int
FileLockHackVMX(ConstUnicode pathName)  // IN:
{
   int err;
   LockValues myValues;

   Unicode lockDir = NULL;
   Unicode entryFilePath = NULL;
   Unicode memberFilePath = NULL;
   Unicode entryDirectory = NULL;

   ASSERT(pathName);

   /* first the locking directory path name */
   lockDir = Unicode_Append(pathName, FILELOCK_SUFFIX);

   /* establish our values */
   myValues.machineID = (char *) FileLockGetMachineID(); // don't free this!
   myValues.executionID = FileLockGetExecutionID();      // free this!
   myValues.locationChecksum = FileLockLocationChecksum(lockDir); // free this!
   myValues.lamportNumber = 0;
   myValues.memberName = NULL;

   LOG(1, ("%s on %s (%s, %s).\n", __FUNCTION__, UTF8(pathName),
       myValues.machineID, myValues.executionID));

   err = CreateEntryDirectory(myValues.machineID, myValues.executionID,
                              lockDir,
                              &entryDirectory, &entryFilePath,
                              &memberFilePath, &myValues.memberName);

   if (err != 0) {
      goto bail;
   }

   /* Scan the lock directory */
   err = Scanner(lockDir, ScannerVMX, &myValues, FALSE);

   if (err == 0) {
      /* if no members are valid, clean up */
      if (myValues.lamportNumber == 1) {
         FileDeletionRobust(pathName, FALSE);
      }
   } else {
      if (vmx86_debug) {
         Warning(LGPFX" %s clean-up failure for '%s': %s\n",
                 __FUNCTION__, UTF8(pathName), strerror(err));
      }
   }

   /* clean up */
   FileRemoveDirectoryRobust(entryDirectory);
   FileRemoveDirectoryRobust(lockDir);

bail:

   Unicode_Free(lockDir);
   Unicode_Free(entryDirectory);
   Unicode_Free(entryFilePath);
   Unicode_Free(memberFilePath);
   Unicode_Free(myValues.memberName);
   free(myValues.locationChecksum);
   free(myValues.executionID);

   return err;
}
void *
FileLockIntrinsic(ConstUnicode pathName,   // IN:
                  Bool exclusivity,        // IN:
                  uint32 msecMaxWaitTime,  // IN:
                  const char *payload,     // IN:
                  int *err)                // OUT:
{
   FILELOCK_FILE_HANDLE handle;
   LockValues myValues;

   Unicode lockDir = NULL;
   Unicode entryFilePath = NULL;
   Unicode memberFilePath = NULL;
   Unicode entryDirectory = NULL;

   ASSERT(pathName);
   ASSERT(err);

   /* Construct the locking directory path */
   lockDir = Unicode_Append(pathName, FILELOCK_SUFFIX);

   /* establish our values */

   myValues.machineID = (char *) FileLockGetMachineID(); // don't free this!
   myValues.executionID = FileLockGetExecutionID();      // free this!
   myValues.payload = (char *) payload;
   myValues.lockType = exclusivity ? LOCK_EXCLUSIVE : LOCK_SHARED;
   myValues.lamportNumber = 0;
   myValues.locationChecksum = FileLockLocationChecksum(lockDir); // free this!
   myValues.waitTime = 0;
   myValues.msecMaxWaitTime = msecMaxWaitTime;
   myValues.memberName = NULL;

   LOG(1, ("Requesting %s lock on %s (%s, %s, %u).\n",
       myValues.lockType, UTF8(pathName), myValues.machineID,
       myValues.executionID, myValues.msecMaxWaitTime));

   /*
    * Attempt to create the locking and entry directories; obtain the
    * entry and member path names.
    */

   *err = CreateEntryDirectory(myValues.machineID, myValues.executionID,
                               lockDir,
                               &entryDirectory, &entryFilePath,
                               &memberFilePath, &myValues.memberName);

   switch (*err) {
   case 0:
      break;

   case EROFS:
      /* FALL THROUGH */
   case EACCES:
      if (!exclusivity) {
         /*
          * Lock is for read/shared access however the lock directory could
          * not be created. Grant an implicit read lock whenever possible.
          * The address of a private variable will be used for the lock token.
          */

         Warning(LGPFX" %s implicit %s lock succeeded on '%s'.\n",
                 __FUNCTION__, LOCK_SHARED, UTF8(pathName));

         *err = 0;
         memberFilePath = &implicitReadToken;
      }

      /* FALL THROUGH */
   default:
      goto bail;
   }

   ASSERT(Unicode_LengthInCodeUnits(memberFilePath) -
          Unicode_LengthInCodeUnits(pathName) <= FILELOCK_OVERHEAD);

   /* Attempt to create the entry file */
   *err = FileLockOpenFile(entryFilePath, O_CREAT | O_WRONLY, &handle);

   if (*err != 0) {
      /* clean up */
      FileRemoveDirectoryRobust(entryDirectory);
      FileRemoveDirectoryRobust(lockDir);

      goto bail;
   }

   /* what is max(Number[1]... Number[all lockers])? */
   *err = Scanner(lockDir, NumberScan, &myValues, FALSE);

   if (*err != 0) {
      /* clean up */
      FileLockCloseFile(handle);
      FileDeletionRobust(entryFilePath, FALSE);
      FileRemoveDirectoryRobust(entryDirectory);
      FileRemoveDirectoryRobust(lockDir);

      goto bail;
   }

   /* Number[i] = 1 + max([Number[1]... Number[all lockers]) */
   myValues.lamportNumber++;

   /* Attempt to create the member file */
   *err = CreateMemberFile(handle, &myValues, entryFilePath, memberFilePath);

   /* Remove entry directory; it has done its job */
   FileRemoveDirectoryRobust(entryDirectory);

   if (*err != 0) {
      /* clean up */
      FileDeletionRobust(entryFilePath, FALSE);
      FileDeletionRobust(memberFilePath, FALSE);
      FileRemoveDirectoryRobust(lockDir);

      goto bail;
   }

   /* Attempt to acquire the lock */
   *err = Scanner(lockDir, WaitForPossession, &myValues, TRUE);

   switch (*err) {
   case 0:
      break;

   case EAGAIN:
      /* clean up */
      FileDeletionRobust(memberFilePath, FALSE);
      FileRemoveDirectoryRobust(lockDir);

      /* FALL THROUGH */
   default:
      break;
   }

bail:

   Unicode_Free(lockDir);
   Unicode_Free(entryDirectory);
   Unicode_Free(entryFilePath);
   Unicode_Free(myValues.memberName);
   free(myValues.locationChecksum);
   free(myValues.executionID);

   if (*err != 0) {
      Unicode_Free(memberFilePath);
      memberFilePath = NULL;

      if (*err == EAGAIN) {
         *err = 0; // lock not acquired
      }
   }

   return (void *) memberFilePath;
}
Exemple #15
0
int main(int argc, const char * argv[])
{


    /*
     Check input switches
    */
    
    int i=0;
    for (i=0; i < argc; i++)
    {
        if (strcmp(argv[i], "-v") == 0)
        {
            shouldPrintStackTrace = 1;
        }
        else if ( strcmp(argv[i], "-l") == 0)
        {
            shouldPrintLexeme = 1;
        }
        else if (strcmp(argv[i], "-a") == 0)
        {
            shouldPrintAssemblyCode = 1;
        }
    }
    
    //  opens input.txt
    originalInputFileWithPCode = fopen(originalInputFileLocation, "r");

    //  scans in the input and saves it to lexemelist inside the Scanner file
    Scanner(originalInputFileWithPCode);

    
    //  opens and handles the parser call
    //  closes file after so we can open to be read later for the virtual machine
    FILE *mcodeOutput = fopen("mcode.txt", "w");
    
    Parser(tokenList);
    printMcodeToFile(mcodeOutput);
    fclose(mcodeOutput);
    
    //  virtual machine
    mcodeOutput = fopen("mcode.txt", "r" );
    

    
    VirualMachine(mcodeOutput,shouldPrintStackTrace);
    
    //  places print statements here so that if it has to print out anything it it finishes running before printing any of the files out to console
    //  handles prints by printing already made files char by char
    
    if (shouldPrintLexeme == 1) {
        int c;
        //FILE *file;
        lexemeList = fopen("lexemelist.txt", "r");
        if (lexemeList) {
            while ((c = getc(lexemeList)) != EOF)
                putchar(c);
            fclose(lexemeList);
        }
        printf("\n");
        
            if (errorOccured == 0) {
                printf("No errors, program is syntactically correct.\n");
            }
    }
    
    if (shouldPrintAssemblyCode == 1) {
        
        printf("\n");
        printf("Assembly Code:\n");
        int c;
        //FILE *file;
        mcodeOutput = fopen("mcode.txt", "r");
        if (mcodeOutput) {
            while ((c = getc(mcodeOutput)) != EOF)
                putchar(c);
            fclose(mcodeOutput);
        }
        printf("\n");

    }
    
    //  if the -v argument was made then it goes through and prints everything in the file
    if (shouldPrintStackTrace == 1) {
        printf("\n");

        int c;
        FILE *file;
        file = fopen("stacktraceTemp.txt", "r");
        if (file) {
            while ((c = getc(file)) != EOF)
                putchar(c);
            fclose(file);
        }
        printf("\n");
        
    }
    
    fclose(originalInputFileWithPCode);
    
    
    return 0;
}
Exemple #16
0
int main (int argc, char *argv[])
{
    // argc should be 4 for correct execution
    if (argc != 4)
    {
        std::cout << "Wrong input. Usage: strassen mode dimension inputfile" << std::endl;
        return 1;
    }

    // get parameters
    else
    {
        const unsigned short int mode = atoi(argv[1]);
        std::cout << mode << std::endl;
        const unsigned int dimension = atoi(argv[2]);
        char * inputfile = argv[3];

        switch(mode)
        {
          // Read inout from the file
          case 0:
          {
            std::ifstream infile;
            infile.open (inputfile);
            unsigned int len = dimension*dimension;
            char* line = (char*) malloc(sizeof(char)*10);
            if (infile.is_open())
            {
              int * dataA = (int*) malloc(sizeof(int)*len);
              int * dataB = (int*) malloc(sizeof(int)*len);
              if(dataA == NULL || dataB == NULL)
              {
                std::cout << "error allocating memory" << std::endl;
                return 1;
              }
              for (unsigned int i = 0; i < len; ++i)
              {
                infile >> line;
                dataA[i] = atoi(line);
              }
              for (unsigned int j = 0; j < dimension; ++j)
              {
                for (unsigned int i = 0; i < dimension; ++i)
                {
                  infile >> line;
                  dataB[i*dimension+j] = atoi(line);
                }
              }
              free(line);

              // input matrices to work with
              Scanner matrixA = Scanner(dataA, true, dimension, dimension, dimension, dimension);
              Scanner matrixB = Scanner(dataB, false, dimension, dimension, dimension, dimension);
              MatrixOps matmath = MatrixOps();
              Scanner matrixC = matmath.strassensWrapper(matrixA, matrixB);
              std::cout << matrixC.current() << std::endl;
              matrixC.nextInRow();
              for (unsigned int i = 1; i < dimension; i++)
              {
                std::cout << matrixC.nextInColumn() << std::endl;
                matrixC.nextInRow();
              }
              std::cout << std::endl;
              free(dataA);
              free(dataB);
            }
            infile.close();
            break;
          }
          // used for determining crossover
          case 1:
          {
            MatrixOps matmath = MatrixOps();
            int * dataA = new int[dimension*dimension+1];
            for (unsigned int i = 0; i < dimension; ++i)
            {
              for (unsigned int j = 0; j < dimension; ++j)
              {
                dataA[i * dimension + j] = rand() % 3 - 1;
              }
            }
            int * dataB = new int[dimension*dimension+1];
            for (unsigned int i = 0; i < dimension; ++i)
            {
              for (unsigned int j = 0; j < dimension; ++j)
              {
                dataB[i * dimension + j] = rand() % 3 - 1;
              }
            }

            Scanner A = Scanner(dataA, true, dimension, dimension, dimension, dimension);
            Scanner B = Scanner(dataB, false, dimension, dimension, dimension, dimension);
            double prevTime = DBL_MAX;
            unsigned int bestPoint = -1;
            unsigned int crossPoint = 8;
            while (crossPoint < dimension)
            {
              double runtime = 0;
              clock_t t = clock();
              matmath.strassensWrapper(A, B, crossPoint);
              matmath.unload();
              runtime = (double) (clock() - t) / CLOCKS_PER_SEC * 1000;
              std::cout << "Crosspoint: " << crossPoint << std::endl;
              std::cout << "Runtime: " << runtime << std::endl;
              if (prevTime > runtime)
              {
                bestPoint = crossPoint;
                prevTime = runtime;
              }
              crossPoint *= 2;
            }
            std::cout << "Best crossover point: " << bestPoint << std::endl;
            free(dataA);
            free(dataB);
            return 0;
          }
          // used for determining average runtime for 3 trials
          case 2:
          {
            MatrixOps matmath = MatrixOps();
            for (unsigned int i = 2; i <= 4096; i *= 2)
            {
              int * dataA = new int[i * i + 1];
              for (unsigned int j = 0; j < i; ++j)
              {
                for (unsigned int k = 0; k < i; ++k)
                {
                  dataA[j * i + k] = rand() % 3 - 1;
                }
              }
              int * dataB = new int[i*i+1];
              for (unsigned int j = 0; j < i; ++j)
              {
                for (unsigned int k = 0; k < i; ++k)
                {
                  dataB[j * i + k] = rand() % 3 - 1;
                }
              }
              Scanner A = Scanner(dataA, true, i, i, i, i);
              Scanner B = Scanner(dataB, false, i, i, i, i);
              double averageTime = 0;
              for (unsigned int j = 0; j < 3; ++j)
              {
                double runtime = 0;
                clock_t t = clock();
                matmath.strassensWrapper(A, B);
                matmath.unload();
                runtime = (double) (clock() - t) / CLOCKS_PER_SEC * 1000 / 3;
                averageTime += runtime;
              }
              std::cout << "Dimension: " << i << std::endl;
              std::cout << "Average runtime: " << averageTime << std::endl;
              free(dataA);
              free(dataB);
            }
            return 0;
          }
          case 3:
          {
            MatrixOps matmath = MatrixOps();
            int * dataA = new int[dimension*dimension+1];
            for (unsigned int i = 0; i < dimension; ++i)
            {
              for (unsigned int j = 0; j < dimension; ++j)
              {
                dataA[i * dimension + j] = j;
              }
            }
            int * dataB = new int[dimension*dimension+1];
            for (unsigned int i = 0; i < dimension; ++i)
            {
              for (unsigned int j = 0; j < dimension; ++j)
              {
                dataB[i * dimension + j] = j;
              }
            }

            Scanner A = Scanner(dataA, true, dimension, dimension, dimension, dimension);
            Scanner B = Scanner(dataB, false, dimension, dimension, dimension, dimension);
            Scanner C = matmath.strassensWrapper(A, B, 4);
            C.print();
            free(dataA);
            free(dataB);
            return 0;
          }
      }
    }