/*****************************************************************
* BiffSocko
* stackerbacker.c
*
* reads in a file and prints it backwards. This uses a stack
* and strtok to tokenize all the words to pop into the stack
*****************************************************************/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
/**********************************
* Structure for node (stack entry)
*********************************/
typedef struct node {
char *str;
struct node *next;
} STACKNODE;
/********************************
* Some function definitions
*******************************/
void push(char *key, STACKNODE **stack);
char *pop(STACKNODE **stack);
int isempty(STACKNODE *stack);
/********************************
* and away we go
*******************************/
int main (int argc, char *argv[]){
char line[1024];
STACKNODE *stack;
FILE *Fp;
char *seperator = " ";
char *tok;
/********************************
* check command line args and
* open the imput file
*******************************/
if(argc != 2){
printf("%s [filename]\n",argv[0]);
exit(1);
}
if(!(Fp=fopen(argv[1],"r"))){
printf("cant open %s .. exiting\n", argv[1]);
exit(1);
}
/********************************
* read in the file and tokenize
* the words and push each word
* onto the stack
*******************************/
stack = NULL;
while((fgets(line, 1024, Fp)) != NULL){
tok = strtok(line, seperator);
while(tok != NULL){
push(tok, &stack);
tok=strtok(NULL, seperator);
}
}
/********************************
* while the stack is not empty
* pop each token from the stack
*******************************/
while(!isempty(stack)){
printf("%s ", pop(&stack));
}
printf("\n");
return 0;
}
/*****************************
* function push()
*****************************/
void push(char *token, STACKNODE **stack) {
STACKNODE *newnode;
newnode = (STACKNODE *)malloc(sizeof(STACKNODE));
newnode->str = strdup(token);
newnode->next = (*stack);
(*stack) = newnode;
}
/*****************************
* function pop()
*****************************/
char *pop(STACKNODE **stack) {
STACKNODE *oldnode;
char *key;
char *retval;
oldnode = (*stack);
key = (*stack)->str;
(*stack) = (*stack)->next;
free(oldnode);
retval = calloc(strlen(key)+1, sizeof(char));
strcpy(retval, key);
return retval;
free(retval);
}
/*****************************
* function isempty()
*****************************/
int isempty(STACKNODE *stack) {
return stack == NULL;
}