Exemple #1
0
void testing(int testArray[], int arrayLength)
{
    int i;
    Stack * stack;
    // create a stack
    stack = createStack();
    // loop for the length of the test data array
    for (i = 0; i < arrayLength; i++)
    {
        //  add an item to the stack
        push(stack, testArray[i]);
        //  print the stack
        printf("List print loop number %d: ", (i+1));
        printStack(stack);
    }
    //    test pop
    printf("Removing the top value from the stack...\n'%d' was just removed from the stack\n", pop(stack));
    //    test peek
    printf("The top value now is: %d\n", peek(stack));
    //    test print stack
    printf("The stack contains the following: ");
    printStack(stack);
    //    test length
    printf("The length of the stack is: %d\n", stackLength(stack));
    //    test destroy stack
    destroyStack(stack);
}
Exemple #2
0
int main (void)
{
	Stack * s = createStack();

	int x;
	for (x = 0; x < 5; x++)
		push(s, x);

	printf ("Stack contents: '");
	printStack (s);
	printf ("'\n");

	for (x = 0; x < 2; x++)
	{
		printf ("popped: %d  stack is now: '", pop(s));
		printStack (s);
		printf ("'\n");
	}

	destroyStack (s);
	printf ("Stack contents: '");
	printStack (s);
	printf ("'\n");

	return 0;
}
Exemple #3
0
//------------------------------------------------------------
//clear or destroy
int 
clear( bvs_ptr tree )
{
  ptr_IStackA stack = newStack( sizeof(node_ptr) ); //zasobnik ukazatelov
  if ( stack == NULL )
    return TREE_ERROR;
    
    
  node_ptr curr_node = tree->root; // korenovy ukazatel
  node_ptr ptr;                    //pomocny ukazatel uzla
  
  while ( (curr_node != NULL) || (SEmpty(stack) != 1) )
  {
    if (curr_node == NULL){
      curr_node = *((node_ptr * )Stop(stack));
      Spop(stack);
      }
    else
    {
      if (curr_node->right != NULL)     //ulozenie praveeho podstromu
        Spush(stack, &(curr_node->right));
        
      ptr = curr_node;
      curr_node=curr_node->left;
      destroyNode(ptr);
      free(ptr);      
    }      
  }
  destroyStack(stack);
  free(stack);
  return TREE_OK;
}
void destroyStack(Stack * stack)
/*This function deallocates the memory allocated by the stack.*/
{
  if(stack == NULL){return;}//base case: return to free the current stack
  destroyStack(stack -> next);//check all the nodes on the stack
  free(stack);//free the memory
}
Exemple #5
0
int* inorderTraversal(struct TreeNode* root, int* returnSize) {
    Stack S;
    struct TreeNode *node;
    int *arr;
    int i = 0;
    initStack(&S);
    arr = (int*)malloc(100 * sizeof(int));
    node = root;
    while(node || !isEmpty(S))
    {
        while(node)
        {
            push(&S, node);
            node = node->left;
        }
        if(!isEmpty(S))
        {
            pop(&S, &node);
            *(arr + i) = node->val;
            i++;
            node = node->right;
        }
        
    }
    destroyStack(&S);
    *returnSize = i;
    return arr;
}
Exemple #6
0
int evaluateExpression(char *expression){
	Token *token;
	Stack *numberStack=createStack();
	Stack *operatorStack=createStack();

	if(expression ==NULL){
		Throw(ERR_NO_ARGUMENT);
	}
	Text *newText=textNew(expression);
	String *tokenizer = stringNew(newText);
	
	
	token=getToken(tokenizer);
	if(token->type == IDENTIFIER_TOKEN){
		Throw(ERR_NOT_ACCEPT_IDENTIFIER);
	}else{
	while(token!=NULL){
		if(isOperator(token)){
			if(((Operator*)token)->info->affix!=PREFIX)
			tryConvertToPrefix((Operator*)token);
		stackPush(token,operatorStack);
		}else if(isNumber(token)){
			stackPush(token,numberStack);
			break;
		}else
			Throw(ERR_INVALID_IDENTIFIER);
		token=getToken(tokenizer);
		if(token==NULL)
			break;
	}
		
	}
	
	while((token=getToken(tokenizer))!=NULL ){
		evaluatePostfixesPrefixesAndInfixes(expression,token,numberStack,operatorStack);
	}
	evaluateAllOperatorOnStack(numberStack,operatorStack);
	Number *result=(Number*)stackPop(numberStack);
	destroyStack(numberStack);
	if(operatorStack !=NULL){
		destroyStack(operatorStack);
	}
	return result->value;
	
}
void CDTUndoWidget::setMapCanvas(QgsMapCanvas *mapCanvas)
{
    if (mMapCanvas == mapCanvas)
    {
        return;
    }
    destroyStack();
    mMapCanvas = mapCanvas;
}
Exemple #8
0
int main(){
    
    Stack * stack1;
    stack1 = createStack();
    
    Element *e1, *e2, *e3, *e4, *e5;
    int a, b, c, d, e;
    
    
    a = 1;
    b = 2;
    c = 3;
    
    e1 = createElement(&a);
    e2 = createElement(&b);
    e3 = createElement(&c);
    
    int empty = isEmpty(stack1);
    if (empty == 1)
        printf("The stack is empty!\n");
    else 
        printf("Why is the stack not empty?\n");
    
    /* Add a Element to the stack and check if the stack is empty*/
    push(stack1, e1);
    
    empty = isEmpty(stack1);
    
    if (empty == 1)
        printf("Why is the stack empty?\n");
    else 
        printf("The stack is not empty!\n");
    
    /* Add another Element to the stack and check it is at the top 
    by calling peek() */
    
    push(stack1, e2);
    Element * test;
    test = peek(stack1);
    printf("The top element is: %d\n", *(int *)(test->elementPtr));
    
    /* remove the top element and test with peek() */
    test = pop(stack1);
    test = peek(stack1);
    printf("The top element is: %d\n", *(int *)(test->elementPtr));
    
    /* Add another and check with peek() */
    push(stack1, e3);
    test = peek(stack1);
    printf("The top element is: %d\n", *(int *)(test->elementPtr));
    
    destroyStack(stack1);
    
    return 0;
}
Exemple #9
0
int main() {
	Stack stack;
	int d0,d1,d2,d3,d4;
	
	
	d0 = 20;
	d1 = 2;
	d2 = 493;
	d3 = 3938;
	d4 = 932837;
	
#ifdef MEMPOOL
	allocMem(BLOCKS,sizeof(StackElement));
#endif

	if ( initStack(&stack, NULL) != 0 ) {
		fprintf(stderr, "An error occurred while initializing a stack\n");
		return -1;
	}
	
	if ( push(&stack , &d0) != 0) {
		fprintf(stderr, "An error occurred while adding an element\n");
		return -1;
	}
	if ( push(&stack , &d1) != 0) {
		fprintf(stderr, "An error occurred while adding an element\n");
		return -1;
	}
	if ( push(&stack , &d2) != 0) {
		fprintf(stderr, "An error occurred while adding an element\n");
		return -1;
	}
	if ( push(&stack , &d3) != 0) {
		fprintf(stderr, "An error occurred while adding an element\n");
		return -1;
	}
	if ( push(&stack , &d4) != 0) {
		fprintf(stderr, "An error occurred while adding an element\n");
		return -1;
	}
	
	int *d5;
	pop(&stack, (void **)&d5);
	
	printf("Top => %d\n",*d5);
	
	traverseStack(&stack);
	
	destroyStack(&stack);
	
#ifdef MEMPOOL	
	freeMemory();
#endif
	return 0;
}
Exemple #10
0
void destroyTP(ThreadPool * TP){
  int i;
  for(i=0;i<TP->totalThreads;i++){
    pthread_join(TP->threads[i],NULL);
  }
  free(TP->threads);
  pthread_mutex_destroy(&TP->mut);
  pthread_cond_destroy(&TP->empty);
  destroyStack(TP->stack);
  free(TP);
}
Exemple #11
0
void QgsUndoWidget::layerChanged( QgsMapLayer * layer )
{
  if ( layer )
  {
    setUndoStack( layer->undoStack() );
  }
  else
  {
    destroyStack();
  }
  emit undoStackChanged();
}
void CDTUndoWidget::setMapLayer( QgsMapLayer * layer )
{
    if ( layer != NULL )
    {
        setUndoStack( layer->undoStack() );
    }
    else
    {
        destroyStack();
    }
    emit undoStackChanged();
}
Exemple #13
0
/*
mark nodal domain containing grid[i][j] as counted
non-recursive version

inputs:
        grid    - 2d array of function values
	counted - 2d array indicating whether a point has been counted
	i       - row of initial point in grid
        j       - column of initial point in grid
	nd      - number of current nodal domain
	ny      - rows in grid
	nx      - columns in grid

precondition: grid and counted are ny x nx

outputs:
         return value: area of domain (in pixels)
         updates stats
*/
int findDomain(bit_array_t *signs, bit_array_t *counted, int i, int j, int nd, int ny, int nx) {
  stack *s = newStack();
  push(s, j, i);
  bit_array_set(counted, j, i);

  int x, y;
  int currentSign;
  int size = 0;

  while (pop(s, &x, &y)) {
    size++;
    currentSign = bit_array_get(signs, j, i);
    
    #ifdef DEBUG
    domain_numbers[y][x] = nd;
    #endif

    // orthongal directions
    // left
    if (x >= 1 && !bit_array_get(counted, x-1, y)) {
      if (bit_array_get(signs, x-1, y) == currentSign) {
        bit_array_set(counted, x-1, y);
        push(s, x - 1, y);
      }
    }

    // above
    if (y >= 1 && !bit_array_get(counted, x, y-1)) {
      if (bit_array_get(signs, x, y-1) == currentSign) {
        bit_array_set(counted, x, y-1);
        push(s, x, y-1);
      }
    }

    // right
    if (x < nx-1 && !bit_array_get(counted, x+1, y)) {
      if (bit_array_get(signs, x+1, y) == currentSign) {
        bit_array_set(counted, x+1, y);
        push(s, x+1, y);
      }
    }

    // below
    if (y < ny-1 && !bit_array_get(counted, x, y+1)) {
      if (bit_array_get(signs, x, y+1) == currentSign) {
        bit_array_set(counted, x, y+1);
        push(s, x, y+1);
      }
    }
  }
  destroyStack(s);
  return size;
}
Exemple #14
0
/*
mark nodal domain containing grid[i][j] as counted
non-recursive version

inputs:
        grid    - 2d array of function values
        counted - 2d array indicating whether a point has been counted
        i       - row of initial point in grid
        j       - column of initial point in grid
        nd      - number of current nodal domain
        ny      - rows in grid
        nx      - columns in grid

precondition: grid and counted are ny x nx

outputs:
         return value: area of domain (in pixels)
         updates stats
*/
int findDomainNoInterp(double **grid, bit_array_t *counted, int i, int j, int nd, int ny, int nx) {
  stack *s = newStack();
  push(s, j, i);
  bit_array_set(counted, j, i);

  int x, y;
  int currentSign;
  int size = 0;

  while (pop(s, &x, &y)) {
    size++;
    currentSign = SIGN(grid[i][j]);

    // orthongal directions
    // left
    if (x >= 1 && !bit_array_get(counted, x-1, y)) {
      if (SIGN(grid[y][x-1]) == currentSign) {
        bit_array_set(counted, x-1, y);
        push(s, x - 1, y);
      }
    }

    // above
    if (y >= 1 && !bit_array_get(counted, x, y-1)) {
      if (SIGN(grid[y-1][x]) == currentSign) {
        bit_array_set(counted, x, y-1);
        push(s, x, y-1);
      }
    }

    // right
    if (x < nx-1 && !bit_array_get(counted, x+1, y)) {
      if (SIGN(grid[y][x+1]) == currentSign) {
        bit_array_set(counted, x+1, y);
        push(s, x+1, y);
      }
    }

    // below
    if (y < ny-1 && !bit_array_get(counted, x, y+1)) {
      if (SIGN(grid[y+1][x]) == currentSign) {
        bit_array_set(counted, x, y+1);
        push(s, x, y+1);
      }
    }
  }
  destroyStack(s);
  return size;
}
Exemple #15
0
/*******************************************************************************************
 *	This function is to evaluate the expression which contains numbers and operators and
 *	return the results in number form.
 *	This function is a prototype function which use as reference to
 *	improve in the evaluateExpression(char*expression) function.
 *	Thus, this function could not evaluate expression like -2,*2,(((2))), +-+-2... *
 *	input  : expression
 *	output : none
 *	return : ((Number*)token)->value
 *
********************************************************************************************/
int evaluate(char *expression){
	Token *token;
	Number *result;

	Stack *numberStack=createStack();
	Stack *operatorStack=createStack();
	if(expression ==NULL){
		Throw(ERR_NO_ARGUMENT);
	}
	Text *newText=textNew(expression);
	String *tokenizer = stringNew(newText);
	while((token=getToken(tokenizer))!=NULL ){
		if(isNumber(token)){
			stackPush(token,numberStack);
		} else if(isOperator(token)) {
			if(((Operator*)token)->info->id==OPENING_BRACKET_OP || ((Operator*)token)->info->id==CLOSING_BRACKET_OP) {
				tryEvaluatePrefixOperatorOnStackThenPush((Operator*)token,numberStack,operatorStack);
			} else{
				tryEvaluateOperatorOnStackThenPush((Operator*)token,numberStack,operatorStack);
			}
		}
	}
	if(operatorStack == NULL){
		operatorPrefixEvaluate(numberStack ,(Operator*)token);
	}else{
		evaluateAllOperatorOnStack(numberStack,operatorStack);
	}
	result=(Number*)stackPop(numberStack);
	destroyStack(numberStack);
	if(operatorStack !=NULL){
		destroyStack(operatorStack);
	}

	return result->value;

}
Exemple #16
0
int main(int argc, char * argv[]) { 
  TokenType ttype;
  source = stdin;
  listing = stdout;

  struct stack_t *scannerStack = newStack(); //track tags

  int relevant = 0; //track if current tag section is relevant to print -- 0 is relevant, > 0 is irrelevant, < 0 is no tags

  while((ttype=getToken()) != ENDFILE) {
    /* if open tag, push onto stack */
    if(ttype == 1) {
      push(scannerStack, formatToken(ttype, tokenString));
      if(relevant > 0) relevant++; //increment relevant flag for any tag inside irrelevant tag
      else if(!compareToken(top(scannerStack))) relevant++; //increment relevant flag on irrelevant tag
    }
    /* if close tag, check top of stack for matching open tag */
    if(ttype == 2) {
      /* if close tag does not match top of stack, report error */
      if(top(scannerStack) == NULL || strcmp(top(scannerStack), formatToken(ttype, tokenString))) {
        if(relevant == 0) printf("-- Error: CLOSE-TAG </%s> with no matching open tag at top of stack at line %d\n", formatToken(ttype, tokenString), lineno);
        continue;
      }
      /* if close tag matches top of stack, pop */
      else {
        pop(scannerStack);
        /* decrement relevant tag on pop if greater than 0 */
        if(relevant > 0) {
          relevant--;
          continue;
        }
      }
    }
    /* print tokens if relevant and tag is on stack */
    if(relevant == 0 && top(scannerStack) != NULL) printToken(ttype, tokenString);
  }

  /* print off remaining tags in stack as errors */
  while(top(scannerStack)) {
    printf("-- Error: OPEN-TAG <%s> with no closing tag left over in stack\n", top(scannerStack));
    pop(scannerStack);
  }

  destroyStack(&scannerStack);
  return 0;
}
Exemple #17
0
void DFSNonRecurTraverse(graph *g, void (*visitFunc)(char e))
{
    visitFunc = print;
    int v = 0, w = 0;
    char elem = 0;
    for(v = 0; v < g->verNum; v++)
        visited[v] = 0;
    stack *s = (stack*)malloc(sizeof(stack));
    initStack(s);
    for(v = 0; v < g->verNum; v++)
    {
        if(!visited[v])
        {
            push(s, g->vertex[v]);
            (*visitFunc)(g->vertex[v]);
            visited[v] = 1;
            v = firstAdjVex(g, v);
        }
        while(!stackEmpty(*s))
        {
            if(!visited[v])
            {
                push(s, g->vertex[v]);
                visited[v] = 1;
                (*print)(g->vertex[v]);
                v = firstAdjVex(g, v);
            }
            else
            {
                getTop(s, &elem);
                w = findIndex(*g, elem);
                v = nextAdjVex(g, w, v);
            }
            if(v == -1)
            {
                pop(s, &elem);
                w = findIndex(*g, elem);
                v = nextAdjVex(g, w, v);
            }
        }
    }
    destroyStack(s);
    s->stackSize = 0;
    free(s);
    s = NULL;
}
void inOrderNonRecursive(struct binaryTreeNode *root) {
    struct Stack *s = createStack();
    while (1) {
        while (root) {
            push(s, root);
            // Got left subtree and keep on adding to stack
            root = root->left;
        }
        if (isEmptyStack(s))
            break;
        root = pop(s);
        printf("%d ", root->data);
        // Indicates completion of left subtree and current node, now go to right subtree
        root = root->right;
    }

    destroyStack(s);
}
int main()
{
    Stack S;
    int data;
    initStack(&S);
    push(&S, 1);
    push(&S, 2);
    pop(&S, &data);
    printf("data = %d\n", data);
    pop(&S, &data);
    printf("data = %d\n", data);
    push(&S, 3);
    pop(&S, &data);
    printf("data = %d\n", data);
    if(!isEmpty(S))
        printf("not empty\n");
    else
        printf("empty\n");
    destroyStack(&S);
    return 0;
}
HuffNode * readInput(char* filename)
/*This function read the input file, and create a Huffman tree based on the command of the input file.*/
{
  FILE * inputfile = fopen(filename, "r");//open the file first
  if(inputfile == NULL){return NULL;}//if the file cannot be opened,return NULL pointer to indicate the user with an error message.

  int temp = fgetc(inputfile);//get the first character of the input file
  Stack * stack = NULL;//create a stack pointer with NULL content
  while(temp != EOF)//if the first character of the input is not end of the file, then we can run the following command.
  {
    if(temp == push)//if the command is push, then run the following.
    {
      temp = fgetc(inputfile);//get the value which needs to be pushed onto the stack
      if(temp == EOF)//if the value is end of the file, then there is something wrong with input file.
      {
        fclose(inputfile);//close the file and return NULL to indicate the user with an error message.
        return NULL;
      }
      HuffNode * temp_node = create_node(temp);//create a temparary Huffman node
      stack = stack_push(stack, temp_node);//push the node into the top of the stack
    }
    else if(temp == pop)//if the command is pop, then run the following
    {
      if(stack_count(stack) == 1){break;}//There must be two nodes on the stack to do the pop command.If not, then just stop and do nothing.
      HuffNode * right = stack_peek(stack);//check the what in the current stack, which contains the right child of the new Huffman node
      stack = stack_pop(stack);//then pop out the current stack
      HuffNode * left = stack_peek(stack);//do the same thing to check the left child of the new Huffman node
      stack = stack_pop(stack);//then pop out the nonused stack
      HuffNode * new_node = stack_node(left, right);//create a new HUffman node, and assign the left and right to the Huffmand node
      stack = stack_push(stack, new_node);//then push the new Huffman node on top of the stack
    }
    temp = fgetc(inputfile);//get the next character with file pointer
  }

  fclose(inputfile);//after reading all the input commands, close the input file
  HuffNode * input_list = stack_peek(stack);//get the node contained in the current stack
  destroyStack(stack);//deallocate the memory used to contain the stack
  return input_list;
}
// pre order using non recursive way
void preOrderNonRecursive(struct binaryTreeNode *root) {
    struct Stack *s = createStack();

    while (1) {
        while (root) {
            // Process current node
            printf("%d ", root->data);
            push(s, root);

            // If left subtree exists, add to stack
            root = root->left;
        }

        if (isEmptyStack(s))
            break;

        root = pop(s);
        // Indicate completion of left subtree and current node, now to to right subtree
        root = root->right;
    }

    destroyStack(s);
}
Exemple #22
0
int main (int argc, const char * argv[]) {
	
	stackNode *myStack;
	
	char lineBuffer[100];
	FILE *inputFile = NULL;
	char *strPtr;
	int counter = 0;
	
	myStack = createStack();
	
    if (argc != 2) {
		printf ("Usage Error: please  path/to/executable path/to/input/file\n");
		exit(1);
	}
    /* open the file for reading */
	inputFile = fopen (argv[1], "r");

	if (inputFile == NULL) {
		printf ( "Error. Input file does not exist!\n");
		exit(1);
	}
	/* this code will read the lines of the file in one at a time.
	it is up to you to add in the code to make it work with your stack */
	else {
		while (fgets (lineBuffer, 10, inputFile) != NULL) {
		    counter++;
		    lineBuffer[strlen(lineBuffer)-1] = '\0';
		    if (strlen(lineBuffer) > 1) {
			    strPtr = &lineBuffer[2];
			    if (lineBuffer[0] == 'P') {
			        push(myStack, strPtr);
		        }
		    }
		    else if (strlen(lineBuffer) == 1) {
		        if (lineBuffer[0] == 'O') {
		            printf("popped: %s\n", pop(myStack));
		        }
		        else if (lineBuffer[0] == 'K') {
		             printf("peeked: %s\n", peek(myStack));
		        }
		        else if (lineBuffer[0] == '$') {
		            printf("current stack: ");
		            printStack(myStack);
		            printf("\n");
		        }
		        else {
		            printf("%s:%d error: unknown symbol '%c'.\n", argv[1], counter, lineBuffer[0]);
		        }
		    }
		    else {
		        printf("%s:%d error: unknown string.\n", argv[1], counter);
		    }
		}
		fclose(inputFile);
	}
	
	destroyStack(myStack);
	
	return 0;
}
 void teardown()
 {
     destroyStack(atStack);
 }
void CDTUndoWidget::onDockClear()
{
    destroyStack();
    this->setEnabled(false);
    this->setVisible(false);
}
Exemple #25
0
//===================================================================
// Cleans up and frees all data
//===================================================================
void cleanupData(DATA_HEAD *data) {
    destroyBST(data->pTree, freeBST);
    destroyStack(data->pStack);
    free(data->pHash);
    free(data);
}
Exemple #26
0
// main() implements a command-based interface that lets you push(), pop(), and
// peek(), all while showing a little diagram that represents the state of the
// stack. You can create a new stack at any time, and you get to set the
// maximum capacity of the stack(s) you create.
int main()
{
    char buffer[128]; int n;
    Stack *myStack = NULL;

    printf("\n");
    printf("Stack ops:\n");
    printf("\n");
    printf("  new <n>    -- create a new stack with capacity set to <n>\n");
    printf("  destroy    -- completely destroy the current stack\n");
    printf("  push <n>   -- push <n> onto the stack\n");
    printf("  pop        -- pops the top element off the stack\n");
    printf("  pop        -- prints the stack's top element without removing it\n");
    printf("  isempty    -- indicates whether the stack is empty\n");
    printf("  isfull     -- indicates whether the stack is full\n");
    printf("\n");

    do
    {
        printf("Enter a command ('?' for help, or 'exit' to quit).\n");
        printf("%% ");

        scanf("%s", buffer);

        if (strcmp(buffer, "?") == 0)
        {
            printf("\n");
            printf("Stack ops:\n");
            printf("\n");
            printf("  new <n>    -- create a new stack with capacity set to <n>\n");
            printf("  destroy    -- completely destroy the current stack\n");
            printf("  push <n>   -- push <n> onto the stack\n");
            printf("  pop        -- pops the top element off the stack\n");
            printf("  pop        -- prints the stack's top element without removing it\n");
            printf("  isempty    -- indicates whether the stack is empty\n");
            printf("  isfull     -- indicates whether the stack is full\n");
        }

        else if (strcmp(buffer, "new") == 0)
        {
            if (myStack != NULL)
                destroyStack(myStack);

            scanf("%d", &n);
            myStack = createStack(n);
        }

        else if (strcmp(buffer, "destroy") == 0)
        {
            if (myStack != NULL)
                myStack = destroyStack(myStack);
        }

        else if (strcmp(buffer, "push") == 0)
        {
            scanf("%d", &n);
            push(myStack, n);
        }

        else if (strcmp(buffer, "pop") == 0)
        {
            n = pop(myStack);

            if (n != INT_MIN)
                printf("\n   -> popped %d\n", n);
        }

        else if (strcmp(buffer, "peek") == 0 || strcmp(buffer, "top") == 0)
        {
            n = peek(myStack);

            if (n != INT_MIN)
                printf("\n   -> peek: %d\n", n);
        }

        else if (strcmp(buffer, "empty") == 0)
        {
            if (isEmpty(myStack))
                printf("\n   -> stack is empty\n");
            else
                printf("\n   -> stack is not empty\n");
        }

        else if (strcmp(buffer, "full") == 0)
        {
            if (isFull(myStack))
                printf("\n   -> stack is full\n");
            else
                printf("\n   -> stack is not full\n");
        }

        else if (strcmp(buffer, "exit") == 0)
        {
            break;
        }

        if (myStack != NULL && !isEmpty(myStack))
            printStack(myStack);

        printf("\n");

    } while (1);

    destroyStack(myStack);

    return 0;
}
Exemple #27
0
void destroy_queue(){
    destroyStack(&s1);
    destroyStack(&s2);
}
Exemple #28
0
/* extract files from the archive as specified by the names argument in argv */
void extractFar(Stack stk, Stack errStk, char **argv)
{
	FILE *achv = fopen(argv[ARCHIVE], "r");
	if(!achv)
	{
		//archive does not exist
		fprintf(stderr,"(%s) does not exist\n", argv[ARCHIVE]);
		exit(EXIT_FAILURE);
	}

	while(!feof(achv))
	{
		char tempName[PATH_MAX];
		int numBytes = -1;
		int fileMode = -1;
		if(fscanf(achv, "%s%d%d", tempName, &numBytes, &fileMode) && numBytes >= 0)
		{
			char fileName[strlen(tempName)];
			strcpy(fileName,tempName);

			char c;
			if((c = fgetc(achv)) != '\n' && c != EOF)			//skip newline
			{
				DIE("%s is corrupt\n",argv[ARCHIVE]);
			}

			//write contents of buffer to new file if exists in stack or empty stack given (extract all)
			if(existsInArchive(stk,fileName) || !stk)
			{
				//create all the required folders if they don't exist and then write to file
				if(fileMode == 0)	//skip directories
				{
					createDir(fileName);
					FILE *f = fopen(fileName,"w");
					if(f)
					{
						int i;
						for(i = 0; i < numBytes; i++)
						{
							fputc(fgetc(achv),f);
						}
						fclose(f);
					}
				}
				else	//if fileName is dir then just make a new directory
				{
					mkdir(fileName,0777);
				}
				if(errStk)
				{
					//if the file is extracted, pop out its pathName from the error stack
					popElement(&errStk,fileName);
				}
			}
			else
			{
				fseek(achv,numBytes,SEEK_CUR);
			}
		}
	}
		
	while(errStk)
	{
		//print out all the errors
		//for checking whether the path is a directory or a file
		struct stat fileStat;
		//check if the path in stack is a directory..in which case don't print to stderr
		if(!stat(errStk->fullPath,&fileStat) && !S_ISDIR(fileStat.st_mode))
		{
			fprintf(stderr,"cannot extract the directory %s\n", errStk->fullPath);
		}
		errStk = popStack(errStk);
	}
	destroyStack(stk);
}
Exemple #29
0
void executeProgram(Program* program) {

	Stack stack;
	int arg_pos;

	initStack(&stack, program->size * 16, MAX_ARG_SIZE);
	if(stack.elements == NULL)
		return;

	program->lineNumber = 0;

	while(program->lineNumber < program->size) {
		char* line;
		
		line = &program->lines[program->lineNumber*MAX_LINE_SIZE];

		if((arg_pos = parseCmd(PUSH_CMD, line)) > 0) {
			pushElement(&stack, line+arg_pos);
			program->lineNumber++;
		}
		else if((arg_pos = parseCmd(POP_CMD, line)) > 0)	{
			char* element;
			int len;

			element = (char *) popElement(&stack);

			len = strnlen(element, MAX_ARG_SIZE);
			memset(element, 0, len);

			program->lineNumber++;
		}
		else if((arg_pos = parseCmd(ADD_CMD, line)) > 0) {
			int a, b, ret;
			char *a_str;
			char *a_element;
			char *b_element;
			int len;

			a_element = popElement(&stack);
			b_element = popElement(&stack);

			a = strn2int(a_element, MAX_ARG_SIZE);
			b = strn2int(b_element, MAX_ARG_SIZE);
			a += b;
			a_str = itoaB10(a); 

			len = strnlen(a_element, MAX_ARG_SIZE);
			memset(a_element, 0, len);

			len = strnlen(b_element, MAX_ARG_SIZE);
			memset(b_element, 0, len);

			len = strlen(a_str);
			pushElement(&stack, a_str);
			
			ret = deallocate(a_str, len); 
			if (ret != 0)
				_terminate(11);

			program->lineNumber++;
		}
		else if((arg_pos = parseCmd(PRINT_CMD, line)) > 0) {
			int ret, len;
			char *element;

			element = (char *) popElement(&stack);
			ret = transmit_all(STDOUT, element, strnlen(element, MAX_ARG_SIZE));
			if (ret != 0)
				_terminate(14);			
			ret = transmit_all(STDOUT, NEWLINE, strnlen(NEWLINE, MAX_ARG_SIZE));
			if (ret != 0)
				_terminate(15);	

			len = strnlen(element, MAX_ARG_SIZE);
			memset(element, 0, len);

			program->lineNumber++;
		}
		else if((arg_pos = parseCmd(COPY_CMD, line)) > 0) {
			int copy_num;
			int ret, i;

			copy_num = strn2int(line+arg_pos, MAX_ARG_SIZE);
			if(copy_num < 1) {
				program->lineNumber++;
				continue;
			}

			char *element;
			element = popElement(&stack);

			for(i=0; i<copy_num; i++) {
				pushElement(&stack, element);
			}

			program->lineNumber++;
		} else
			program->lineNumber++;

	}

	destroyStack(&stack);

}