Hello. I'm having some issues with an assignment here. In my LOAD function, the root is being overwritten on each pass of the for loop.
Code:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
struct myTree
{
char *first;
char *last;
long number;
struct myTree *right, *left;
};
typedef struct myTree node;
int SCAN(FILE *(*stream))
{
int size = 0;
*stream = fopen("hw9.data", "r");
char *buffer = NULL;
size_t bufsize = 0;
size_t temp = getline(&buffer, &bufsize,*stream);
//Increment size for each line break until the end of the file
while(!feof(*stream))
{
size++;
temp = getline(&buffer, &bufsize, *stream);
}
return size;
}
void INSERT(node *(*tree), node *item)
{
if(!*tree)
{
*tree = item;
return;
}
else
{
if(strcmp((*tree)->first, item->first) < 0)
{
INSERT(&(*tree)->left, item);
}
else
{
INSERT(&(*tree)->right, item);
}
}
}
void LOAD(FILE *stream, int size, node *(*root))
{
int i;
char *tempText;
size_t lineLen;
node *item = (node *)malloc(sizeof(node));
rewind(stream);
getline(&tempText, &lineLen, stream);
item->first = strtok(tempText, " ");
item->last = strtok(NULL, " ");
item->number = (long)strtok(NULL, "\n");
*root = item;
for(i = 0; i < size + 1; i++)
{
printf("\n\n%s\n\n", item->first);
if(i == 0){
*root = item;}
//INSERT(root, item);
printf("\n\nroot %s\n\n", (*root)->first);
getline(&tempText, &lineLen, stream);
item->first = strtok(tempText, " ");
item->last = strtok(NULL, " ");
item->number = (long)strtok(NULL, "\n");
}
fclose(stream);
}
void FREE(node *tree)
{
if(tree == NULL)
{
return;
}
FREE(tree->left);
FREE(tree->right);
free(tree);
}
int main(void) {
int size;
FILE *stream;
node *tree = NULL;
size = SCAN(&stream);
LOAD(stream, size, &tree);
system("clear");
//Print statements not needed to show errors.
/*printf("\nPRE_ORDER\n");
printf("--------------\n");
PRE_ORDER(tree);
printf("\nIN_ORDER\n");
printf("--------------\n");
IN_ORDER(tree);
printf("\nPOST_ORDER\n");
printf("--------------\n");
POST_ORDER(tree);*/
FREE(tree);
tree = NULL;
return 0;
}
Here is my data file:
Code:
ronald johnson 7774013
john ronson 7774014
tomas smith 7774015
won ton 7774016
On loop iteration 1, the root is correctly assigned as ronald. On iteration 2, it is reassigned to john, then on iteration 3, it is reassigned to tomas, and so on.
How can I correct this issue?