Reading from a file of names, I'm trying to put those name into a binary search tree. But for some reason when I read the file, I am starting with a random junk file node:
TreeNode* read_from_file(const char* file){
File *fp = fopen(file,"r");
char buffer[MAX_NAME_LEN];
TreeNode *t = NULL;
t = insert(t,buffer); //insert is just your standard function for creating a binary tree
while(!feof(fp)){
fscanf(fp,"%s",buffer);
insert(t,buffer);
}
return t;
fclose(fp);
}
When I then print out the tree I am getting a seemingly random node in my list such as '{ or ÐFÀ> along with the name nodes when the inputed file only has names like bob matt and nick.
You insert buffer
before you fill it with anything. The random trash is just what happens to be in that array before you do anything with it yourself.
Obvious solution: remove the first insert
. (As a matter of fact, I can't think of a reason why it's there anyway.) Since you need to save the starting node t
somewhere, to return it at the end, you need to re-think your loop. Either insert a dummy string as 'root' (but not using the uninitialized buffer
!), or do an fscanf
before the loop.