I am trying to load words from a text file into a binary search tree.
Each line of the file contains one word.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct node node;
struct node {
node *left, *right;
char *key;
};
node *newnode(char *key)
{
node *n = malloc(sizeof(node));
n->key = malloc(sizeof(key));
strcpy(n->key, key);
n->right = n->left = NULL;
return n;
}
node *insirtNode(node *root, char *key)
{
if (!root)
return newnode(key);
if (strcmp(key, root->key) < 0)
root->left = insirtNode(root->left, key);
else if (strcmp(key, root->key) > 0)
root->right = insirtNode(root->right, key);
return root;
}
void readFromFileToTree(const char *fname, node **root)
{
// read each line
FILE *s = fopen(fname, "r");
if (!s) {
printf("101");
exit(0);
}
char *t = NULL;
do {
char temp[100];
t = fgets(temp, 40, s); // printf("%s ",temp); to check what words are being insirting and whats not
*root = (node *)insirtNode(*root, temp);
} while (t);
fclose(s);
}
int main()
{
node *root = NULL;
readFromFileToTree("anas.txt", &root);
return 0;
}
the code stops before reading every word from the file and returns -1073740940