I took Salem's suggestion and started simple, and was able to slightly modify my push() function to properly push "hello" and "world" onto the stack (and also have them echo out correctly). I also made the current "instance" of the Stack non-global. However, after attempting to re-implement the file handling and the fscanf(), The issue I run into is that the first value is the only one being added to the stack. The correct number of times -- just not the correct data. This leads me to believe it's an issue with the code that follows
Code:
char *str1 = malloc(128);
...
within the main() function. Again, however, I can't seem to wrap my head around what exactly the pointer issue is. But, because the "hello" and "world" test cases worked successfully, I'm fairly certain it's an issue with the way I'm addressing the strings after delimiting the file.
Thanks in advance, you guys are super helpful!
Updated code (a bit has changed):
Code:
#include <stdio.h>
#include <assert.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
/*global variable to track current number of elements in stack*/
int STACK_ELEMENTS = 0;
/*struct for a new Node*/
typedef struct node {
char *value;
struct node *next;
} Node;
/*struct for a Stack*/
typedef struct my_stack {
Node *head;
} Stack;
/*determines if stack is empty or not*/
bool stack_isEmpty() {
if (STACK_ELEMENTS < 1)
return true;
else
return false;
}
/*push a new node onto the current stack*/
/*return the new head node*/
Node *push(Node **currHead, char *val) {
Node *tempNode = malloc(sizeof(Node));
tempNode -> value = val;
tempNode -> next = *currHead;
*currHead = tempNode;
STACK_ELEMENTS++;
return (*currHead);
}
/*pop off current top node of the stack and return its value*/
char *pop(Node **pHead) {
char *val;
/*as long as the head isn't a NULL, ie empty stack*/
if ((*pHead) != NULL) {
Node *tempNode;
tempNode = malloc(sizeof(Node));
tempNode = *pHead;
val = tempNode -> value;
*pHead = tempNode -> next;
free(tempNode);
STACK_ELEMENTS--;
}
else
return 0;
return val;
}
int main(int argc, char *argv[]) {
/*verify arguments*/
if (argc != 3) {
fprintf(stderr, "usage: strrev <file> <newfile>\n");
exit(1);
}
char *fileIn = argv[1];
char *fileOut = argv[2];
/*open file streams*/
FILE *in = fopen(fileIn, "r");
FILE *out = fopen(fileOut, "w");
/*initialize new stack called values*/
Stack *values;
values = malloc(sizeof(Stack));
char *str1 = malloc(128);
while(!feof(in))
{
/*scan, delimiting on semicolon*/
/*if the scanned element does not fit format, break*/
if (fscanf(in, "%[^;];", str1) != 1) {
break;
}
push(&(values -> head), str1);
}
/*go through stack until it's empty, writing each popped value to a file*/
/*this will accomplish reversal due to LIFO*/
while(!stack_isEmpty()) {
fprintf(out,"%s;", pop(&(values -> head)));
}
free(str1);
fclose(in);
fclose(out);
return 0;
}