Ejemplo n.º 1
0
  /**
   * Look for a slash-delimited number in string s,
   * and if found set v to the numerical value, and
   * set s to the portion of the string before the
   * first slash. Return true if slash data found,
   * false otherwise.
   */
  bool extractSlashData(std::string& s, std::string& name, std::string& data) {
    int slen = static_cast<int>(s.size());
    string::size_type n = s.find_first_of("/");
    if (n != string::npos && (static_cast<int>(n) < slen)) {
      int m;
      for (m = static_cast<int>(n)+1; m < slen; m++) if (s[m] == '/') break;
      if (m < slen) {
	data = s.substr(n+1,m-n-1);
	name = s.substr(0,n);
	removeWhiteSpace(name);
	s = s.substr(m+1,1000);
	return true;
      }
      else {
	name = s;
	removeWhiteSpace(name);
	data = "";
	s = "";
	return false;
      }
    }
    else {
      name = s;
      removeWhiteSpace(name);
      data = "";
      s = "";
      return false;
    }
  }
Ejemplo n.º 2
0
void executeRightOneRedirectionForeGround(char *full,char* input,char *half2,char firstHalfArray[][100], int firstHalfArrayCt)
{
	char* fileName = removeWhiteSpace(half2);
 	int copyFD = dup(1);
 	
    close(1);
    open(fileName, O_WRONLY | O_CREAT | O_TRUNC,0660);

	pid_t pid;
	pid = fork();
	
	if(pid<0)
	{
		perror("SamShell: ERROR : 'fork() failed");
	}
	if(pid==0) //Child Process
	{		
		if(firstHalfArrayCt>0)
		{
			execlp(full,input,firstHalfArray,NULL);
		}
		else
		{
			execlp(full,input,NULL);
		}
		perror("SamShell: ERROR : 'execlp() failed\n");

	}
	if(pid>0) //Parent process
	{
			wait(NULL);
			dup2(copyFD,1);
	}
}
Ejemplo n.º 3
0
/**
 * Will parse line and return a vector of attribute pointers
 * @param _strLine line to be parsed
 * @return vector of attribute pointers
 */
vector<Attributes*> getAttributes( string& _strLine )
{  
  vector<Attributes*> vecAttributes;
  string strippedLine;
  
  removeWhiteSpace(_strLine);
  
  int openBracket  = _strLine.find("<") + 1;
  int closeBracket = _strLine.find(">", openBracket);

  strippedLine = _strLine.substr(openBracket, (closeBracket - openBracket));
  
  if (strippedLine.find(" ") == string::npos)
  {
    return vecAttributes;
  }
  
  vector<string> stringSplit = split(strippedLine, " ");
  
  for (string arg : stringSplit)
  {
    if (arg.find("=") != string::npos)
    {
      vecAttributes.push_back(new Attributes(split(arg, "=")));
    }
  }
  return vecAttributes;
}
Ejemplo n.º 4
0
/*This method is used to validate loops*/
int isValidLoop(FILE* inputFile)
{
    /*Used to keep track of tokens, and store lines and tokens*/
    char tokens[1][20], line[100], lineCopy[100], *token;

    /*Used to keep track of current position within text file*/
    fpos_t currentPosition;

    /*Stores current position within text file so the location can be read from again*/
    fgetpos (inputFile,&currentPosition);

    /*This loop is almost the same as the one in the isValidMove() function*/
    /*The only difference is that it checks for an endloop statement and then resets the position in the file after validation*/
    while ( !feof(inputFile) )
    {
        fgets( line, 99, inputFile );
        toLowercase(line);
        strcpy(lineCopy, line);

        token = removeWhiteSpace(strtok( lineCopy, " \t\n" ));

        if (strcmp(token, "\0") == 0 || strncmp(token, "#", 1) == 0)
            continue;

        strcpy(tokens[0], token);
        token = removeWhiteSpace(strtok( NULL, " \t\n" ));

        /*Check for endloop command*/
        if (strcmp(tokens[0], "endloop") == 0 && token == NULL)
        {
            /*Go back to position in file before validation*/
            fsetpos (inputFile,&currentPosition);
            return true;
        }

        /*Check if moves within file are valid*/
        if (isValidMove(line, inputFile) == false)
            return false;
    }

    return false;
}
Ejemplo n.º 5
0
int GetIntText(Widget text, int *value)
{
    char *strValue, *endPtr;
    int retVal;

    strValue = XmTextGetString(text);		/* Get Value */
    removeWhiteSpace(strValue);			/* Remove blanks and tabs */
    *value = strtol(strValue, &endPtr, 10);	/* Convert string to long */
    if (strlen(strValue) == 0)			/* String is empty */
	retVal = TEXT_IS_BLANK;
    else if (*endPtr != '\0')			/* Whole string not parsed */
    	retVal = TEXT_NOT_NUMBER;
    else
	retVal = TEXT_READ_OK;
    XtFree(strValue);
    return retVal;
}
Ejemplo n.º 6
0
int main(void) {

	const char* t1 = "This is a test sentence to see if\nwhitespace removal is working";
	const char* t2 = "gggThis tests if lstrip is working";
	const char* t3 = "This tests if rstrip is workinghhh";
	const char* t4 = "000 this tests is strip is working 000";
	const char* t5 = "this tEsts if UpPer is WorkINg";
	const char* t6 = "THIS TESTS if LOwEr is WORKInG"; 

	printf("%s\n %s\n\n", t1, removeWhiteSpace(t1));
	printf("%s\n %s\n\n", t2, lstrip(t2, 'g'));
	printf("%s\n %s\n\n", t3, rstrip(t3, 'h'));
	printf("%s\n %s\n\n", t4, strip(t4, '0'));
	printf("%s\n %s\n\n", t5, upper(t5));
	printf("%s\n %s\n\n", t6, lower(t6));
	

	return 0;
}
Ejemplo n.º 7
0
void parsePipedInput(char pIn[]) { //checks for redirection

	pIn = removeWhiteSpace(pIn);
	int wordstotal = strlen(pIn);

	//printf("%s\n", pIn);

	int head = 0;
	for (i = 0; i < strlen(pIn); i++) {
		//printf("start with %d  ", i);

		if (pIn[i] == '>') {
			//printf("redirection > found\n");
			redirectionFlag = 1;
			if (pIn[i + 1] == '>') { //">>老 版快"
				//printf("another redirection > found\n");
				i = i + 2;
				head = i;
				dupRedirection(pIn, i, ">>");

			} else { //">"老 版快
				i = i + 1;
				head = i;
				dupRedirection(pIn, i, ">");
			}
		} else if (pIn[i] == '<') { //"<"老 版快"
			//printf("redirection < found\n");
			redirectionFlag = 1;

			i = i + 1;
			head = i;
			dupRedirection(pIn, i, "<");
		}
		//printf("end %d \n", i);
	}

	strcpy(currentInput, pIn);
	strtok(currentInput, "<");
	strtok(currentInput, ">");
	//printf("curin: %s\n", currentInput);
	//printf("outside for-loop \n");
}//end of parsePipedInput()
Ejemplo n.º 8
0
  static double getNumberFromString(std::string s) {
    bool inexp = false;
    removeWhiteSpace(s);
    int sz = static_cast<int>(s.size());
    char ch;
    for (int n = 0; n < sz; n++) {
      ch = s[n];
      if (!inexp && (ch == 'E' || ch == 'e' || ch == 'D' || ch == 'd')) 
	inexp = true;
      else if (ch == '+' || ch == '-') {
	if (n > 0 && (s[n-1] != 'E' && s[n-1] 
		      != 'e' && s[n-1] != 'd' && s[n-1] != 'D')) {
	  return UNDEF;
	}
      }
      else if (ch != '.' && (ch < '0' || ch > '9')) {
	return UNDEF;
      }
    }
    return de_atof(s);
  }
Ejemplo n.º 9
0
void executeRightTwoRedirectionForeGround(char *full,char* input,char *half2,char firstHalfArray[][100], int firstHalfArrayCt)
{
	char* fileName = removeWhiteSpace(half2);
	int fileFd = open(fileName, O_WRONLY | O_APPEND,0660);
    if(fileFd==-1)
    {
    	fprintf(stderr, "\nERROR : no such file to append to (%s)\n",fileName );
    	close(fileFd);
    	return;
    }
 	int copyFD = dup(1);
 	
    dup2(fileFd,1);

	pid_t pid;
	pid = fork();
	
	if(pid<0)
	{
		perror("SamShell: ERROR : 'fork() failed");
	}
	if(pid==0) //Child Process
	{		
		if(firstHalfArrayCt>0)
		{
			execlp(full,input,firstHalfArray,NULL);
		}
		else
		{
			execlp(full,input,NULL);
		}
		perror("SamShell: ERROR : 'execlp() failed\n");

	}
	if(pid>0) //Parent process
	{
			wait(NULL);
			dup2(copyFD,1);
	}
}
Ejemplo n.º 10
0
/**
 * This function will print out all data specific to the parserState provided
 * @param _vecToPrint  vector all all elements
 * @param _lineState   ParserState of line from XML File
 * @param _lineNum     current line's number
 * @param _strLine     current line
 * @param _lastElement The tag name of the last opening tag
 */
void printXMLData( vector<Element*>& _vecToPrint, ParserState& _lineState, 
        int _lineNum, string& _strLine, string _lastElement )
{
  //if ( == ELEMENT_OPENING_TAG)
  if (1 == 1)
  {
    // Remove whitespace from the line
    removeWhiteSpace(_strLine);

    // Print line number and content
    cout << _lineNum << ". " << _strLine << endl;
    cout << "---------------------------------------------------------------------" << endl;

    // Print line parser state
    ShowState(_lineState);

    // Handle parser state specific actions
    if (_lineState == ELEMENT_OPENING_TAG)
    {    
      cout << "-- Adding '" << _lastElement << "' to Vector (Stack)" << endl;
      printVector(_vecToPrint);
    }
    else if (_lineState == ELEMENT_CLOSING_TAG)
    {
      cout << "-- Removing '" << _lastElement << "' from Vector (Stack)" << endl;
      printVector(_vecToPrint);
    }
    else if (_lineState == ELEMENT_NAME_AND_CONTENT || _lineState == SELF_CLOSING_TAG)
    {
      if (_lineState == ELEMENT_NAME_AND_CONTENT)
      {
        cout << "--   TAG NAME: '" << _lastElement << "'" << endl;
        cout << "--   TAG CONTENT: '" << getTagContent(_strLine) << "'" << endl;
      }

      cout << "-- Vector (Stack) unchanged" << endl;
    }
  }
}
Ejemplo n.º 11
0
void executeLeftRedirectionForeGround(char *full,char* input,char *half2,char firstHalfArray[][100], int firstHalfArrayCt)
{
	char* fileName = removeWhiteSpace(half2);
 	int copyFD = dup(0);
	int fd = open(fileName, O_RDONLY  ,0660);
	if(fd==-1)
	{
	 fprintf(stderr, "\nERROR : no such file to read from (%s)\n",fileName );
     close(fd);
     return;	
	}
	dup2(fd,0);
	close(fd);

 	pid_t pid;
	pid = fork();
	
	if(pid<0)
	{
		perror("SamShell: ERROR : 'fork() failed");
	}
	if(pid==0) //Child Process
	{		
		if(firstHalfArrayCt>0)
		{
			execlp(full,input,firstHalfArray,NULL);	
		}
		else
		{
			execlp(full,input,NULL);	
		}
	}
	if(pid>0) //Parent process
	{
			wait(NULL);
			dup2(copyFD,0);
	}
}
ArithmeticExpression::ArithmeticExpression(string in) {	//constructor with 1 parameter (string in)
	int openBrackets = 0;		//openBrackets counts how many '(' are in the expression
	int closedBrackets = 0;		//closedBrackets counts how many ')' are in the expression
	splitIndex = 0;				//index of the operator
	input = in;					//sets input as string parameter (the expression)
	input = removeWhiteSpace(input);	//removes white space in the expression
	input = removeBrackets(input);		//removes outer excess brackets in the expression

	//checks addition and subtraction
	for (unsigned int i=0; i<input.length(); i++) {	//for each character in the expression
		char b = '0';		//placeholder for b when i = 0
		if (i > 0)
			b = input.at(i-1);	//b is the character before c
		char c = input.at(i);	//c is the current character being looked at in the expression
		if (c == '(' )			//if c is an open bracket,
			openBrackets++;		//add one to openBrackets.
		else if (c == ')' )		//if c is a closed bracket,
			closedBrackets++;	//add one to closedBrackets.
		else if ((c == '+' || (c == '-' && b != '(')) && openBrackets == closedBrackets) {	//if c is operator + or - and number of '(' == number of ')',
			splitIndex = i;		//sets splitIndex to the index of the operator.
		}
	}

	//checks multiplication and division
	if (splitIndex == 0) {		//if there are no more + or - operators, looks for * or /
		for (unsigned int i=0; i<input.length(); i++) {
			char c = input.at(i);
			if (c == '(' )
				openBrackets++;
			else if (c == ')' )
				closedBrackets++;
			else if ((c == '*' || c == '/') && openBrackets == closedBrackets)	//if c is operator * or / and number of brackets are equal,
				splitIndex = i;		//sets splitIndex to the index of the operator
		}
	}
}
Ejemplo n.º 13
0
void dupRedirection(char *pIn, int i, char *type) {

	char filepath[500];
	int len = strcspn(pIn + i, "<>");
	ncpy(filepath, pIn + i, len);
	char* rmspace = removeWhiteSpace(filepath);

	//printf("dupred: [%s] [%s] [%s] [%d]\n", pIn + i, rmspace, type, len);

	if (!strcmp(type, ">>")) {
		int fd = open(rmspace, O_APPEND | O_CREAT | O_RDWR, 0666);
		dup2(fd, 1);
		close(fd);
	} else if (!strcmp(type, ">")) {
		int fd = open(rmspace, O_CREAT | O_RDWR, 0666);
		dup2(fd, 1);
		close(fd);
	} else if (!strcmp(type, "<")) {
		int fd = open(rmspace, O_RDWR);
		dup2(fd, 0);
		close(fd);
	}

}
Ejemplo n.º 14
0
static int stringToPref(const char *string, PrefDescripRec *rsrcDescrip)
{
    int i;
    char *cleanStr, *endPtr, **enumStrings;
    
    switch (rsrcDescrip->dataType) {
      case PREF_INT:
	cleanStr = removeWhiteSpace(string);
	*(int *)rsrcDescrip->valueAddr =
		strtol(cleanStr, &endPtr, 10);
	if (strlen(cleanStr) == 0) {		/* String is empty */
	    *(int *)rsrcDescrip->valueAddr = 0;
	    XtFree(cleanStr);
	    return False;
	} else if (*endPtr != '\0') {		/* Whole string not parsed */
    	    *(int *)rsrcDescrip->valueAddr = 0;
	    XtFree(cleanStr);
    	    return False;
    	}
	XtFree(cleanStr);
	return True;
      case PREF_BOOLEAN:
      	cleanStr = removeWhiteSpace(string);
      	for (i=0; i<N_BOOLEAN_STRINGS; i++) {
      	    if (!strcmp(TrueStrings[i], cleanStr)) {
      	    	*(int *)rsrcDescrip->valueAddr = True;
      	    	XtFree(cleanStr);
      	    	return True;
      	    }
      	    if (!strcmp(FalseStrings[i], cleanStr)) {
      	    	*(int *)rsrcDescrip->valueAddr = False;
      	    	XtFree(cleanStr);
      	    	return True;
      	    }
      	}
      	XtFree(cleanStr);
      	*(int *)rsrcDescrip->valueAddr = False;
    	return False;
      case PREF_ENUM:
      	cleanStr = removeWhiteSpace(string);
      	enumStrings = (char **)rsrcDescrip->arg;
      	for (i=0; enumStrings[i]!=NULL; i++) {
      	    if (!strcmp(enumStrings[i], cleanStr)) {
      	    	*(int *)rsrcDescrip->valueAddr = i;
      	    	XtFree(cleanStr);
      	    	return True;
      	    }
      	}
      	XtFree(cleanStr);
      	*(int *)rsrcDescrip->valueAddr = 0;
    	return False;
      case PREF_STRING:
	if ((int)strlen(string) >= (int)rsrcDescrip->arg)
      	    return False;
	strncpy(rsrcDescrip->valueAddr, string, (int)rsrcDescrip->arg);
      	return True;
      case PREF_ALLOC_STRING:
      	*(char **)rsrcDescrip->valueAddr = XtMalloc(strlen(string) + 1);
      	strcpy(*(char **)rsrcDescrip->valueAddr, string);
      	return True;
    }
    return False;
}
Ejemplo n.º 15
0
int main()
{

 char input[1000];
 char history[999][1000]; 
 // char history[4][1000]; 
 int historyPointerLocation = 0;
 int noOfElementsInHistory = 0;
 while(1)
 {
 	// signal(SIGCHLD, SIG_DFL);
 	printf("\nSamShell-v0.0> ");
 	
 	
 	fgets(input,1000,stdin);
 	char* input2 = removeWhiteSpace(input);
 	
 	strcpy(input,input2);
 	char inputArray[100][100];
 	int inputArrayCount = 0,i=0;

 	splitCommandAndArgs(input,&inputArrayCount,inputArray);

 	if(input[0]=='\0')
 	{
 		continue;
 	}

 	int redirectQ = searchForRedirection(inputArray,&inputArrayCount);
 	if(redirectQ!=0)
 	{
 		redirectionExecution(input, inputArray,&inputArrayCount,&redirectQ);
		int i=0;
 		for(;i<inputArrayCount;i++)
 		{
 			strcat(input," ");
 			strcat(input,inputArray[i]);
 		}
	 	if(historyPointerLocation>998){historyPointerLocation=0;}
		strcpy(history[historyPointerLocation],input);
		historyPointerLocation=historyPointerLocation + 1;
		if(noOfElementsInHistory!=999)
		{
			noOfElementsInHistory = noOfElementsInHistory+1;
		}
 		continue;
 	}

 	int pipeQ = searchForPiping(inputArray,&inputArrayCount);
 	if(pipeQ==1)
 	{
 		pipingExecution(input,inputArray,&inputArrayCount);
 		int i=0;
 		for(;i<inputArrayCount;i++)
 		{
 			strcat(input," ");
 			strcat(input,inputArray[i]);
 		}
	 	if(historyPointerLocation>998){historyPointerLocation=0;}
		strcpy(history[historyPointerLocation],input);
		historyPointerLocation=historyPointerLocation + 1;
		if(noOfElementsInHistory!=999)
		{
			noOfElementsInHistory = noOfElementsInHistory+1;
		}
 		continue;
 	}
 	if((strlen(input))==4)
 	{
 		char temporary[1000];
 		strcpy(temporary,input);
 		int i=0;
 		for(;i<strlen(temporary);i++)
 		{
 			temporary[i] = tolower(temporary[i]);
 		}
	 	if(strncmp(temporary,EXIT,4)==0 || strncmp(temporary,QUIT,4)==0 )
	 	{
	 		printf("\n");
	 		printf(BYE);
	 		printf("\n");
	 		return EXIT_SUCCESS;
	 	}
	 	if(input[0]=='!')
	 	{
	 		if(isdigit(input[1])&&isdigit(input[2])&&isdigit(input[3]))
	 		{
	 			int hundreds = (input[1] - '0')*100;
	 			int tens = (input[2] - '0')*10;
	 			int ones = (input[3] - '0');
	 			int calculatedNumber = hundreds + tens + ones;
	 			if(calculatedNumber>noOfElementsInHistory || calculatedNumber==0)
	 			{
	 				fprintf(stderr,"SamShell: ERROR : '%s': event not found\n",input);
	 				continue;
	 			}
	 			char* temp = searchHistoryUsingNumber(calculatedNumber,&historyPointerLocation,&noOfElementsInHistory,history);
	 			strcpy(input,temp);
	 			splitCommandAndArgs(input,&inputArrayCount,inputArray);
	 			if(strlen(input)==7)
 				{
		 			if(strncmp(input,HISTORY,7)==0)
		 			{
		 			printHistory(history,&historyPointerLocation,&noOfElementsInHistory);
		 			if(historyPointerLocation>998){historyPointerLocation=0;}
			 		strcpy(history[historyPointerLocation],input);
			 		historyPointerLocation=historyPointerLocation + 1;
			 		if(noOfElementsInHistory!=999)
			 		{
			 			noOfElementsInHistory = noOfElementsInHistory+1;
			 		}
		 			 continue;
		 			}
 				}

 				int redirectQIn = searchForRedirection(inputArray,&inputArrayCount);
			 	if(redirectQIn!=0)
			 	{
			 		redirectionExecution(input, inputArray,&inputArrayCount,&redirectQIn);
					int i=0;
			 		for(;i<inputArrayCount;i++)
			 		{
			 			strcat(input," ");
			 			strcat(input,inputArray[i]);
			 		}
		 			if(historyPointerLocation>998){historyPointerLocation=0;}
			 		strcpy(history[historyPointerLocation],input);
			 		historyPointerLocation=historyPointerLocation + 1;
			 		if(noOfElementsInHistory!=999)
			 		{
			 			noOfElementsInHistory = noOfElementsInHistory+1;
			 		}
			 		continue;
			 	}

			 	int pipeQIn = searchForPiping(inputArray,&inputArrayCount);
			 	if(pipeQIn==1)
			 	{
			 		pipingExecution(input,inputArray,&inputArrayCount);
			 		int i=0;
			 		for(;i<inputArrayCount;i++)
			 		{
			 			strcat(input," ");
			 			strcat(input,inputArray[i]);
			 		}
		 			if(historyPointerLocation>998){historyPointerLocation=0;}
			 		strcpy(history[historyPointerLocation],input);
			 		historyPointerLocation=historyPointerLocation + 1;
			 		if(noOfElementsInHistory!=999)
			 		{
			 			noOfElementsInHistory = noOfElementsInHistory+1;
			 		}
			 		continue;
			 	}

			 	if((strlen(input))==2)
			 	{
			 		if(strncmp(input,"cd",2)==0)
			 		{
			 			if(inputArrayCount>=1)
			 			{
			 			 changeDirForeFunction(input,inputArray[0]);
			 			}
			 			else
			 			{
			 			 fprintf(stderr,"SamShell: ERROR : invalid argument for cd\n");
			 			}
			 			int i=0;
				 		for(;i<inputArrayCount;i++)
				 		{
				 			strcat(input," ");
				 			strcat(input,inputArray[i]);
				 		}
			 			if(historyPointerLocation>998){historyPointerLocation=0;}
				 		strcpy(history[historyPointerLocation],input);
				 		historyPointerLocation=historyPointerLocation + 1;
				 		if(noOfElementsInHistory!=999)
				 		{
				 			noOfElementsInHistory = noOfElementsInHistory+1;
				 		}
						   continue;
			 		}
 				}

	 			searchInMyPath(input,inputArray,inputArrayCount);
	 			continue;
	 		}
	 		else
	 		{
	 			
	 			searchInMyPath(input,inputArray,inputArrayCount);
	 			continue;
	 		}
	 	}
 	}	

 	if((strlen(input))==2)
 	{
 		if(strncmp(input,"cd",2)==0)
 		{
 			if(inputArrayCount>=1)
 			{
 			 changeDirForeFunction(input,inputArray[0]);
 			}
 			else
 			{
 			 fprintf(stderr,"SamShell: ERROR : invalid argument for cd\n");
 			}
 			int i=0;
	 		for(;i<inputArrayCount;i++)
	 		{
	 			strcat(input," ");
	 			strcat(input,inputArray[i]);
	 		} 			
 			if(historyPointerLocation>998){historyPointerLocation=0;}
	 		strcpy(history[historyPointerLocation],input);
	 		historyPointerLocation=historyPointerLocation + 1;
	 		if(noOfElementsInHistory!=999)
	 		{
	 			noOfElementsInHistory = noOfElementsInHistory+1;
	 		}
			continue;
 		}
 	}

 	if((strlen(input))==2)
 	{
 		
 		if(input[0]=='!' && input[1]=='!')
 		{
 			if(noOfElementsInHistory!=0)
 			{
 				char* temp;
 				if(historyPointerLocation!=0)
 				{
 					temp = history[historyPointerLocation-1];
 				}
 				else
 				{
 					temp = history[noOfElementsInHistory-1];
 				}
	 			strcpy(input,temp);
	 			splitCommandAndArgs(input,&inputArrayCount,inputArray);

	 			if(strncmp(input,HISTORY,7)==0)
	 			{
	 				printHistory(history,&historyPointerLocation,&noOfElementsInHistory);
	 				continue;
	 			}

	 			int redirectQIn = searchForRedirection(inputArray,&inputArrayCount);
			 	if(redirectQIn!=0)
			 	{
			 		redirectionExecution(input, inputArray,&inputArrayCount,&redirectQIn);
					int i=0;
			 		for(;i<inputArrayCount;i++)
			 		{
			 			strcat(input," ");
			 			strcat(input,inputArray[i]);
			 		}
			 		strcpy(history[historyPointerLocation],input);
			 		historyPointerLocation=historyPointerLocation + 1;
			 		if(noOfElementsInHistory!=4)
			 		{
			 			noOfElementsInHistory = noOfElementsInHistory+1;
			 		}
			 		continue;
			 	}

			 	int pipeQIn = searchForPiping(inputArray,&inputArrayCount);
			 	if(pipeQIn==1)
			 	{
			 		pipingExecution(input,inputArray,&inputArrayCount);
			 		int i=0;
			 		for(;i<inputArrayCount;i++)
			 		{
			 			strcat(input," ");
			 			strcat(input,inputArray[i]);
			 		}

			 		continue;
			 	}

			 	if((strlen(input))==2)
			 	{
			 		if(strncmp(input,"cd",2)==0)
			 		{
			 			if(inputArrayCount>=1)
			 			{
			 			 changeDirForeFunction(input,inputArray[0]);
			 			}
			 			else
			 			{
			 			 fprintf(stderr,"SamShell: ERROR : invalid argument for cd\n");
			 			}
			 			int i=0;
				 		for(;i<inputArrayCount;i++)
				 		{
				 			strcat(input," ");
				 			strcat(input,inputArray[i]);
				 		}
				 		if(historyPointerLocation>998){historyPointerLocation=0;}
				 		strcpy(history[historyPointerLocation],input);
				 		historyPointerLocation=historyPointerLocation + 1;
				 		if(noOfElementsInHistory!=999)
				 		{
				 			noOfElementsInHistory = noOfElementsInHistory+1;
				 		}
						continue;
			 		}
 				}
	 			searchInMyPath(input,inputArray,inputArrayCount);
	 			continue;
 			}
 			else
 			{
 				fprintf(stderr,"SamShell: ERROR : '%s': event not found\n",input);
 				continue;
 			}
 		}
 	}

 	if(input[0]=='!')
 	{
 		int i=1;
 		char *tempo;
 		char prefixString[1000];
 		tempo = strndup(input+1,strlen(input)-1);
 		strcpy(prefixString,tempo);
 		for(i=0;i<inputArrayCount;i++)
 		{
 			strcat(prefixString," ");
 			strcat(prefixString,inputArray[i]);
 		}
 		prefixString[strlen(prefixString)] = '\0';
 		char *temp = searchHistoryUsingPrefix(prefixString,&historyPointerLocation,&noOfElementsInHistory,history);
 		if(temp[0]!='\0')
 		{
 			printf("\ntemp %s\n",temp);
 			strcpy(input,temp);
 			splitCommandAndArgs(input,&inputArrayCount,inputArray);



 			if(strncmp(input,HISTORY,7)==0)
	 			{
	 				printHistory(history,&historyPointerLocation,&noOfElementsInHistory);
	 				continue;
	 			}

	 			int redirectQIn = searchForRedirection(inputArray,&inputArrayCount);
			 	if(redirectQIn!=0)
			 	{
			 		redirectionExecution(input, inputArray,&inputArrayCount,&redirectQIn);
					int i=0;
			 		for(;i<inputArrayCount;i++)
			 		{
			 			strcat(input," ");
			 			strcat(input,inputArray[i]);
			 		}
			 		if(historyPointerLocation>998){historyPointerLocation=0;}
			 		strcpy(history[historyPointerLocation],input);
			 		historyPointerLocation=historyPointerLocation + 1;
			 		if(noOfElementsInHistory!=999)
			 		{
			 			noOfElementsInHistory = noOfElementsInHistory+1;
			 		}
			 		continue;
			 	}

			 	int pipeQIn = searchForPiping(inputArray,&inputArrayCount);
			 	if(pipeQIn==1)
			 	{
			 		pipingExecution(input,inputArray,&inputArrayCount);
			 		int i=0;
			 		for(;i<inputArrayCount;i++)
			 		{
			 			strcat(input," ");
			 			strcat(input,inputArray[i]);
			 		}
			 		if(historyPointerLocation>998){historyPointerLocation=0;}
			 		strcpy(history[historyPointerLocation],input);
			 		historyPointerLocation=historyPointerLocation + 1;
			 		if(noOfElementsInHistory!=999)
			 		{
			 			noOfElementsInHistory = noOfElementsInHistory+1;
			 		}
			 		continue;
			 	}

			 	if((strlen(input))==2)
			 	{
			 		if(strncmp(input,"cd",2)==0)
			 		{
			 			if(inputArrayCount>=1)
			 			{
			 			 changeDirForeFunction(input,inputArray[0]);
			 			}
			 			else
			 			{
			 			 fprintf(stderr,"SamShell: ERROR : invalid argument for cd\n");
			 			}
			 			int i=0;
				 		for(;i<inputArrayCount;i++)
				 		{
				 			strcat(input," ");
				 			strcat(input,inputArray[i]);
				 		}
				 		if(historyPointerLocation>998){historyPointerLocation=0;}
				 		strcpy(history[historyPointerLocation],input);
				 		historyPointerLocation=historyPointerLocation + 1;
				 		if(noOfElementsInHistory!=999)
				 		{
				 			noOfElementsInHistory = noOfElementsInHistory+1;
				 		}
						continue;
			 		}
 				}
	 			searchInMyPath(input,inputArray,inputArrayCount);
	 			continue;
 		}
 		
 	}

 	if(strncmp(input,HISTORY,7)!=0)
	{
 	 searchInMyPath(input,inputArray,inputArrayCount);
 	}

 	if(historyPointerLocation>998){historyPointerLocation=0;}
 	if(inputArrayCount!=0)
 	{
 		for(i=0;i<inputArrayCount;i++)
 		{
 			strcat(input," ");
 			strcat(input,inputArray[i]);
 		}
 	}
 	strcpy(history[historyPointerLocation],input);
 		
 	historyPointerLocation=historyPointerLocation + 1;
    if(noOfElementsInHistory!=999)
 	{
 		noOfElementsInHistory = noOfElementsInHistory+1;
 	}
 	if(strlen(input)==7)
 	{
	 	if(strncmp(input,HISTORY,7)==0)
	 	{
	 		printHistory(history,&historyPointerLocation,&noOfElementsInHistory);
	 		continue;
	 	}
 	}

 	
	
 }
 return EXIT_SUCCESS;
 
}
Ejemplo n.º 16
0
command_t
makeCommandStreamUtil(int (*get_next_byte) (void *),
		      void *get_next_byte_argument,
		      STATE *state)
{
  char **tokenPTR = checked_malloc(sizeof(char**));
  char *token = NULL;
  int len = 0;
  TOKENTYPE type;
  command_t command = NULL;
  char *input = NULL, *output = NULL;

  type = readNextToken(tokenPTR, &len, get_next_byte, get_next_byte_argument);
  if (type == NOT_DEFINED) {
    free(tokenPTR);
    return NULL;
  } else if (type == O_PAR) {
    token = "(";
  } else {
    token = *tokenPTR;
  }

  command = AllocateCommand();
  if (!command) {
    return NULL;
  }


  if (!strncmp(token, "then", 4)) {
    if (!(pop() == IF)) {
      printErr();
    }
    push(THEN);
    *state = THEN;
    goto ret_null;
  } else if (!strncmp(token, "done", 4)) {
    if (!(pop() == DO)) {
      printErr();
    }
    *state = DONE;
    CScount--;
    goto ret_null;
  } else if (!strncmp(token, "do", 4)) {
    STATE tmp = pop();
    if (!((tmp == WHILE) || (tmp == UNTIL))) {
      printErr();
    }
    push(DO);
    *state = DO;
    goto ret_null;
  } else if (!strncmp(token, "else", 4)) {
    if (!(pop() == THEN)) {
      printErr();
    }
    push(ELSE);
    *state = ELSE;
    goto ret_null;
  } else if (!strncmp(token, "fi", 4)) {
    STATE tmp = pop();
    if (!((tmp == THEN) || (tmp == ELSE))) {
      printErr();
    }
    CScount--;
    *state = FI;
    goto ret_null;
  } else if (!strncmp(token, ")", 1)) {
    CScount--;
    *state = CLOSE_PAR;
    goto ret_null;
  } else if (!strncmp(token, "if", 2)) {
    push(IF);
    CScount++;
    command = makeCommand(command, NULL, IF_COMMAND, input, output);
    free(tokenPTR);
    command->u.command[0] = makeCommandStreamUtil(get_next_byte,
						  get_next_byte_argument,
						  state);
    while (*state != THEN) {
      if (!makeCommandStreamUtil(get_next_byte,
				 get_next_byte_argument,
				 state)) {
	type = NOT_DEFINED;
	break;
      }
    }

    if (type == NOT_DEFINED && *state != THEN) {
      return NULL;
    }

    command->u.command[1] = makeCommandStreamUtil(get_next_byte,
						  get_next_byte_argument,
						  state);
    if (*state != ELSE && *state != FI) {
      // HANDLE error;
      ;
    } else if (*state == ELSE || (*state == FI && CScount)) {
	command->u.command[2] = makeCommandStreamUtil(get_next_byte,
						      get_next_byte_argument,
						      state);
    } else {
      command->u.command[2] = NULL;
    }
  } else if (!strncmp(token, "while", 5)) {
    push(WHILE);
    (CScount)++;
    command = makeCommand(command, NULL, WHILE_COMMAND, input, output);
    free(tokenPTR);
    command->u.command[0] = makeCommandStreamUtil(get_next_byte,
						  get_next_byte_argument,
						  state);
    if (*state != DO) {
      // Handle Error
      ;
    }
    command->u.command[1] = makeCommandStreamUtil(get_next_byte,
						  get_next_byte_argument,
						  state);
    if (*state != DONE) {
      // HANDLE error;
      ;
    } else if (*state == DONE) {
      if (checkRedirection(get_next_byte, get_next_byte_argument)) {
	fillRedirectionOperands(&command->input, &command->output,
				get_next_byte, get_next_byte_argument);
      }

      command->u.command[2] = makeCommandStreamUtil(get_next_byte,
      						    get_next_byte_argument,
      						    state);
      /* if (command->u.command[2]) { */
      /* 	command_t newCommand = makeCommand(NULL, NULL, SEQUENCE_COMMAND, */
      /* 					   NULL, NULL); */
      /* 	newCommand->u.command[0] = command->u.command[1]; */
      /* 	newCommand->u.command[1] = command->u.command[2]; */
      /* 	command->u.command[1] = newCommand; */
      /* 	command->u.command[2] = NULL; */
      /* } */

    } else {
      command->u.command[2] = NULL;
    }    
  } else if (!strncmp(token, "until", 5)) {
    push(UNTIL);
    (CScount)++;
    command = makeCommand(command, NULL, UNTIL_COMMAND, input, output);
    free(tokenPTR);
    command->u.command[0] = makeCommandStreamUtil(get_next_byte,
						  get_next_byte_argument,
						  state);
    if (*state != DO) {
      // Handle Error
      ;
    }
    command->u.command[1] = makeCommandStreamUtil(get_next_byte,
						  get_next_byte_argument,
						  state);
    if (*state != DONE) {
      // HANDLE error;
      ;
    } else if (*state == DONE) {
      if (checkRedirection(get_next_byte, get_next_byte_argument)) {
	fillRedirectionOperands(&command->input, &command->output,
				get_next_byte, get_next_byte_argument);
      }
      command->u.command[2] = makeCommandStreamUtil(get_next_byte,
      						    get_next_byte_argument,
      						    state);
      /* if (command->u.command[2]) { */
      /* 	command_t newCommand = makeCommand(NULL, NULL, SEQUENCE_COMMAND, */
      /* 					   NULL, NULL); */
      /* 	newCommand->u.command[0] = command->u.command[1]; */
      /* 	newCommand->u.command[1] = command->u.command[2]; */
      /* 	command->u.command[1] = newCommand; */
      /* 	command->u.command[2] = NULL; */
      /* } */
    } else {
      command->u.command[2] = NULL;
    }    

  } else if (!strncmp(token, "(", 1)) {
    CScount++;
    command = makeCommand(command, NULL, SUBSHELL_COMMAND, input, output);
    free(tokenPTR);
    command->u.command[0] =  makeCommandStreamUtil(get_next_byte,
              get_next_byte_argument,
              state);
    if (*state != CLOSE_PAR) {
      // Handle Error
    } else if (*state == CLOSE_PAR && CScount) {
      command->u.command[0] = makeCommandStreamUtil(get_next_byte,
                get_next_byte_argument,
                state);
    } 
  } else {
    // SIMPLE_COMMAND
    while (1) {
      STATE prevState = *state;
      if (isKeyWordUpdate(token, state) && (prevState == COMMAND)) {
         	removeWhiteSpace(token);
        	command = makeSimpleCommand(command, tokenPTR, input, output);
        	break;
      }
      if (type == REDIRECTION1 || type == REDIRECTION2) {
	type = fillRedirectionOperands(&input,
				       &output,
				       get_next_byte,
				       get_next_byte_argument);

	//	command = makeSimpleCommand(command, tokenPTR, input, output);
	//        break;
	//	type = readNextToken(tokenPTR, &len, get_next_byte, get_next_byte_argument);
      } else if (type == SPACE) {
	appendChar(token, ' ');
	type = readNextToken(tokenPTR, &len, get_next_byte, get_next_byte_argument);
      } else if (type == NEWLINE && !CScount) {
      	command = makeSimpleCommand(command, tokenPTR, input, output);
      	break;
      } else if (type == PIPE || type == SEMICOLON || type == NEWLINE) {
	removeWhiteSpace(token);
	if (((type == PIPE) || (type == SEMICOLON)) && !strlen(token)) {
	  printErr();
	}
	command = makeCommand(command, tokenPTR, 
			      type == PIPE ? PIPE_COMMAND : SEQUENCE_COMMAND,
			      input, output);
	command->u.command[1] = makeCommandStreamUtil(get_next_byte,
						      get_next_byte_argument,
						      state);
	if (!command->u.command[1]) {
	  command = convertToSimple(command);
	}
	break;
      }
      *state = COMMAND;
    }
  }

  return command;
ret_null:
  free(command);
  free(tokenPTR);
  return NULL;
}
Ejemplo n.º 17
0
int GetNextURL(char *html, char *urlofthispage, char *result, int pos) {
  char c;
  int len, i, j;
  char *p1;  //!< pointer pointed to the start of a new-founded URL.
  char *p2;  //!< pointer pointed to the end of a new-founded URL.

  // NEW
  // Clean up \n chars
  if(pos == 0) {
    removeWhiteSpace(html);
  }
  // /NEW

  // Find the <a> <A> HTML tag.
  while (0 != (c = html[pos])) {
    if ((c=='<') &&
        ((html[pos+1] == 'a') || (html[pos+1] == 'A'))) {
      break;
    }
    pos++;
  }
  //! Find the URL it the HTML tag. They usually look like <a href="www.cs.dartmouth.edu">
  //! We try to find the quote mark in order to find the URL inside the quote mark.
  if (c) {
    
    // Added by Matt Mukerjee
    // check for equals first... some HTML tags don't have quotes...or use single quotes instead
    p1 = strchr(&(html[pos+1]), '=');
    
    if ((!p1) || (*(p1-1) == 'e') || ((p1 - html - pos) > 10)) {
      // keep going...
      return GetNextURL(html,urlofthispage,result,pos+1);
    }
    if (*(p1+1) == '\"' || *(p1+1) == '\'')
      p1++;
    // added by Matt Mukerjee
    p1++;    
    // added by Matt Mukerjee
    p2 = strpbrk(p1, "\'\">");
    if (!p2) {
      // Added by Matt Mukerjee
      // keep going...
      return GetNextURL(html,urlofthispage,result,pos+1);
    }
    if (*p1 == '#') { // Why bother returning anything here....recursively keep going...
      // Added by Matt Mukerjee      
      return GetNextURL(html,urlofthispage,result,pos+1);
    }
    if (!strncmp(p1, "mailto:",7))
      return GetNextURL(html, urlofthispage, result, pos+1);
    if (!strncmp(p1, "javascript:",11))   // Added by Xiaochao 
      return GetNextURL(html, urlofthispage, result, pos+1);
    if (!strncmp(p1, "http", 4) || !strncmp(p1, "HTTP", 4)) {
      //! Nice! The URL we found is in absolute path.
      strncpy(result, p1, (p2-p1));
      return  (int)(p2 - html + 1);
    } else {
      //! We find a URL. HTML is a terrible standard. So there are many ways to present a URL.
      if (p1[0] == '.') {
        //! Some URLs are like <a href="../../../a.txt"> I cannot handle this. 
	// again...probably good to recursively keep going..
	// NEW
        
        return GetNextURL(html,urlofthispage,result,pos+1);
	// /NEW
      }
      if (p1[0] == '/') {
        //! this means the URL is the absolute path
        for (i = 7; i < strlen(urlofthispage); i++)
          if (urlofthispage[i] == '/')
            break;
        strcpy(result, urlofthispage);
        result[i] = 0;
        strncat(result, p1, (p2 - p1));
        return (int)(p2 - html + 1);        
      } else {
        //! the URL is a absolute path.
        len = strlen(urlofthispage);
        for (i = (len - 1); i >= 0; i--)
          if (urlofthispage[i] == '/')
            break;
        for (j = (len - 1); j >= 0; j--)
          if (urlofthispage[j] == '.')
              break;
        if (i == (len -1)) {
          //! urlofthis page is like http://www.cs.dartmouth.edu/
            strcpy(result, urlofthispage);
            result[i + 1] = 0;
            strncat(result, p1, p2 - p1);
            return (int)(p2 - html + 1);
        }
        if ((i <= 6)||(i > j)) {
          //! urlofthispage is like http://www.cs.dartmouth.edu/~abc
          //! or http://www.cs.dartmouth.edu
          strcpy(result, urlofthispage);
          result[len] = '/';
          strncat(result, p1, p2 - p1);
          return (int)(p2 - html + 1);
        }
        strcpy(result, urlofthispage);
        result[i + 1] = 0;
        strncat(result, p1, p2 - p1);
        return (int)(p2 - html + 1);
      }
    }
  }    
  return -1;
}
Ejemplo n.º 18
0
/*Main program*/
int main(void)
{
    /*Variable Declarations*/

    /*Used to store lines from text, copies of lines, file name of text, and tokens, respectively*/
    char line[100], lineCopy[100], fileName[100], *token;

    /*Array of keywords that are valid commands*/
    char keywords[8][14] = {"forward", "reverse", "turnright", "turnleft", "pause", "light", "reset", "loop"};

    /*Variable used as a counter*/
    int counter;

    /*Variable used to keep track of line number in text file*/
    int lineCount = 0;

    /*Initializr status of the light*/
    LIGHT_ON = false;

    /*Variable for getting the file from the user*/
    FILE *inputFile;

    /*Makes sure the motors are stationary and the LED is off*/
    parallelput(0);

    /*Prompts user to enter a file name*/
    printf("Enter a file name: ");
    gets(fileName);

    /* Main loop in the program */

    /*If the file is valid and can be read*/
    if ( (inputFile = fopen( fileName, "r" )) != NULL )
    {
        /*While there is another line in the text file*/
        while ( !feof(inputFile) )
        {
            /*Get the line*/
            fgets( line, 99, inputFile );

            /*Convert line to lowecase*/
            toLowercase(line);

            /*Creates a copy of the line for tokenization (which changes original line)*/
            strcpy(lineCopy, line);

            /*Increase line count by 1*/
            lineCount++;

            /*Prevents iteration of previous line if very last line in text file is an empty line*/
            if( feof(inputFile) )
                break;

            /*If the command in the text file is valid*/
            if (isValidMove(lineCopy, inputFile) == true)
            {
                /*Display message*/
                printf("Line #%d: ", lineCount);
                /*creates a copy of the string*/
                strcpy(lineCopy, line);

                /*create a token using line copy*/
                token = removeWhiteSpace(strtok( lineCopy, " \t\n" ));

                /*Checks to see if line is not blank or a comment and displays a message indicating what was on the line*/
                if (token == NULL)
                {
                    printf("empty line\n");
                    continue;
                }

                if(strncmp(token, "#", 1) == 0)
                {
                    printf("comment\n");
                    continue;
                }

                /*Loop used to check if move is one of the following:*/
                /*Forward, backward, turnleft, turnright, pause*/
                for (counter = 0; counter < 5; counter++)
                {
                    /*If the command is one of the following*/
                    if (strcmp(token, keywords[counter]) == 0)
                    {
                        /*Select function to execture based on counter and break out of loop*/
                        chooseMove(counter, atoi(removeWhiteSpace(strtok(NULL, " \t\n"))));
                        break;
                    }
                }

                /*Check to see if the command was to configure the light*/
                if (strcmp(token, keywords[5]) == 0)
                    /*Execute light function*/
                    light(removeWhiteSpace(strtok( NULL, " \t\n" ))) ;

                /*Check to see if the command was reset*/
                if (strcmp(token, keywords[6]) == 0)
                    /*Execute reset function*/
                    reset();

                /*Check to see if the command was a loop*/
                if (strcmp(token, keywords[7]) == 0)
                    /*Adds appropriate number of lines to get current line number and execute loop function*/
                    lineCount += loop(line, atoi(removeWhiteSpace(strtok(NULL, " \t\n"))), inputFile);
            }

            /*If the move is not valid*/
            else
            {
                /*isplay error message indicating the line number in the text file where the error was found*/
                errorMessage(lineCount);

                /*Reset motors and LED and waits for user to press a key then exits*/
                parallelput(0);
                getch();
                return 0;
            }
        }

        /* Display the results */

        /*If there are no more line in the file*/

        /*Notify user that commands are finished execuing*/
        printf("\nReached the end of the file.\nThe program will now exit.\n");

        /*Reset motors and LED and waits for user to press a key then exits*/
        parallelput(0);
        getch();
    }

    /*If file does not exist*/
    else
    {
        /*Notify user that file does not exist*/
        printf("\nThe file does not exist.\nThe program will now exit.\n");

        /*Wait for user to press a key then exits*/
        getch();
    }
}
Ejemplo n.º 19
0
/*This method is used to perform the loop command*/
int loop(char line[], int iterations, FILE* inputFile)
{
    /*This method is very similar to the main() function*/
    /*The only difference is it exectues the instructions iterations number of times*/
    /*In addition, this function returns the number of lines within the loop as the last iteration*/
    /*does not alter current position within text file*/

    /*Same as main() function*/
    char lineCopy[100], *token;
    char keywords[7][14] = {"forward", "reverse", "turnright", "turnleft", "pause", "light", "reset"};
    int counter, counter2;
    int lineCount = 0;

    /*Used to keep track of current position within text file*/
    fpos_t currentPosition;

    /*Stores current position within text file so the location can be read from again*/
    fgetpos (inputFile,&currentPosition);

    strcpy(lineCopy, line);

    /*Display message*/
    printf("loop %d times\n", iterations);

    for (counter = 0; counter < iterations; counter++)
    {
        /*Display message*/
        printf("\niteration #%d:\n", counter+1);
        /*Sets location within text file to line right after loop comand*/
        fsetpos (inputFile,&currentPosition);

        /*random string used so token does not become null after each iteration*/
        token = "reset token";

        /*Executes commands like in main() function as long as command is not endloop*/
        while (strcmp(token, "endloop") != 0)
        {
            fgets( line, 99, inputFile );
            lineCount++;
            strcpy(lineCopy, line);
            toLowercase(lineCopy);

            token = removeWhiteSpace(strtok( lineCopy, " \t\n" ));

            if (token == NULL || strncmp(token, "#", 1) == 0)
                continue;

            for (counter2 = 0; counter2 < 5; counter2++)
            {
                if (strcmp(token, keywords[counter2]) == 0 && counter2 < 5)
                {
                    chooseMove(counter2, atoi(removeWhiteSpace(strtok(NULL, " \t\n"))));
                    break;
                }
            }

            if (strcmp(token, keywords[5]) == 0)
                light(removeWhiteSpace(strtok( NULL, " \t\n" ))) ;

            if (strcmp(token, keywords[6]) == 0)
                reset();

            if (strcmp(token, keywords[7]) == 0)
                loop(line, atoi(removeWhiteSpace(strtok(NULL, " \t\n"))), inputFile);
        }
    }

    /*Display message*/
    printf("\nend loop\n\n");

    /*Returns number of line within the loop (including endloop statement)*/
    return (lineCount / iterations);
}
Ejemplo n.º 20
0
/*This function is used to validate the commands in the text file and returns wheter a move is valid or not (true/ false)*/
int isValidMove(char line[], FILE* inputFile)
{
    /*Instance variables used in tokenization*/
    char *token, tokens[2][20];

    /*Array of all valid keywords (excluding comments)*/
    char keywords[10][14] = {"forward", "reverse", "turnright", "turnleft", "pause", "loop", "light", "reset", "on", "off"};

    /*Counter variable*/
    int counter;

    /*Creates token*/
    token = removeWhiteSpace(strtok( line, " \t\n" ));

    /*If token is empty or begins with a '#', the move is valid (must be a comment or empty line)*/
    if (token == NULL || strncmp(token, "#", 1) == 0)
        return true;

    /*Store the token*/
    else
        strcpy(tokens[0], token);

    /*Create another token*/
    token = removeWhiteSpace(strtok( NULL , " \t\n" ));

    /*If this token is empty and the command was reset*/
    if (token == NULL && strcmp(tokens[0], keywords[7]) == 0)
        return true;

    /*If this token is empty (reset is the only keyword not followed by a word or number)*/
    else if (token == NULL)
        return false;

    else

        /*Store the second token */
        strcpy(tokens[1], token);

    /*Makes sure there is not a third keyword in the line (not a valid command)*/
    if (strtok( NULL, " \t\n" ) == NULL)
    {
        /*Checks to see if the command (first token stored is one of the commands that require a number)*/
        /*Forward, reverse, turnleft, turnrignt, pause, loop*/
        for (counter = 0; counter  < 6; counter++)
        {
            /*If the first token was one of the commands and the second one was a valid number*/
            if (strcmp(tokens[0], keywords[counter]) == 0 && isValidNumber(tokens[1]) == true)
            {
                /*Checks to see if the keyword was a loop (loops require special validation)*/
                if (counter == 5)
                    /*Will either be true or false*/
                    return isValidLoop(inputFile);

                return true;
            }
        }

        /*If the command was light and the second keyword was valid (on/off)*/
        if ((strcmp(tokens[0], keywords[6]) == 0) && (strcmp(tokens[1], keywords[8]) == 0 || strcmp(tokens[1], keywords[9]) == 0))
        {
            return true;
        }
    }

    /*If nothing is true then move must be invalid*/
    return false;
}
Ejemplo n.º 21
0
/**
 * This will loop through the file and extract XML Data.
 * @param _fileName the path to the file which will be read
 */
int XMLReader(string _fileName)
{
  ifstream         infile;           // Input file stream for XML file to parse
  int              intLineCount = 0; // Keep track of line number
  string           strLine = "";     // Hold current line while parsing XML file
  vector<Element*> vecElementStack;  // Will hold all tag names and tag lines
  string previousElementName = "";   // The tag name of the previous element on the vector (stack)
  ParserState currentState = STARTING_DOCUMENT; // Will hold state of previously read line
  
  Element* rootElement = NULL;
  
  infile.open(_fileName, ifstream::in);
  
  if ( infile.fail() )
  {
    cerr << "Error opening '" << _fileName << "'" << endl ;
    return EXIT_FAILURE;
  }
  else
  {
    // Loop through the file
    do
    {
      // Increment line counter
      intLineCount++;
      
      // Read a new line from the file
      getline(infile, strLine);
      
      // Get tag name of previous open tag element (will return "" if none)
      previousElementName = getLastElement(vecElementStack);
      
      // Get state of newly read line
      currentState = GetXMLData(strLine, currentState);
      
      // Handle parser state specific actions
      if (currentState == ELEMENT_OPENING_TAG) //########################## HERE
      {
        Element* tempElement = new Element(intLineCount, strLine, vecElementStack.size(), currentState);
        tempElement->addAttribute(getAttributes(strLine));
        
        if (rootElement == NULL) // First time adding to the tree
        {
          rootElement = tempElement;
        }
        else
        {
          (vecElementStack[ vecElementStack.size() - 1 ])->addChild( tempElement );
        }
        
        vecElementStack.push_back(tempElement);
        previousElementName = getLastElement(vecElementStack);
      }
      else if (currentState == ELEMENT_CLOSING_TAG)
      {
        if (previousElementName != getClosingTagName(strLine))
        {
          // if open tag name != closing tag name
          cout << endl << "*******************************************" << endl;
          cout << "ERROR: Invalid closing tag at Line " << intLineCount << endl;
          cout << "REASON: " << previousElementName << " != " << getClosingTagName(strLine) << endl;
          cout << "ABORTING..." << endl;
          cout << "*******************************************" << endl;
          return EXIT_FAILURE;
        }
        
        vecElementStack.pop_back();
      }
      else if (currentState == ELEMENT_NAME_AND_CONTENT)
      {
        Element* tempElement = new Element(intLineCount, strLine, vecElementStack.size(), currentState);
        tempElement->addAttribute(getAttributes(strLine));
        
        (vecElementStack[ vecElementStack.size() - 1 ])->addChild( tempElement );
      }
      else if (currentState == ERROR)
      {
        removeWhiteSpace(strLine);
        
        cout << endl << "*******************************************" << endl;
        cout << "ERROR: Something went wrong!" << endl;
        cout << "~~ Line " << intLineCount << ": " << strLine << endl;
        cout << "ABORTING..." << endl;
        cout << "*******************************************" << endl;
        return EXIT_FAILURE;
      }
      
      printXMLData(vecElementStack, currentState, intLineCount, strLine, previousElementName);

      cout << endl;
      
    } while (infile.good());
    
    cout << endl << endl << endl << "TREE OUTPUT" << endl;
    cout << "********************************************************" << endl;
    
    RecursivePrint(rootElement);

    deleteVectorData(vecElementStack);
  }
}