Hello all,
I'm currently looking at a very simple program which will read some information from a file, store this in a binary tree, then print it to the screen.
Unfortunately, I'm having problems with it. The program is doing one of those annoying things where it isn't giving me any errors or warning, just crashing when I execute it.
Heres the code for you to digest :
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* construct tree */
struct node
{
char *word;
struct node *left,*right;
};
/* insert into tree*/
struct node *inserttree(struct node *tree, char *s)
{
int i;
if ( tree==NULL )
{
if ( (tree=(struct node *) malloc(sizeof (struct node)))!=NULL )
if ( (tree->word=(char *) malloc(strlen(s)+1))==NULL )
{
free(tree);
tree = NULL;
}
else
{
tree->left = NULL;
tree->right = NULL;
strcpy(tree->word, s);
}
}
else if ( i = strcmp(tree->word, s) > 0 )
tree->left = inserttree(tree->left, s);
else if ( i < 0 )
tree->right = inserttree(tree->right, s);
else
return tree;
}
/* print to console*/
void printtree(struct node *tree, FILE *outf)
{
if ( tree != NULL )
{
printtree(tree->left, outf);
printf("%s\n", tree->word);
printtree(tree->right, outf);
}
}
/* destroy tree */
void freetree(struct node *tree)
{
if ( tree!=NULL )
{
free(tree->word);
freetree(tree->left);
freetree(tree->right);
free(tree);
}
}
int main(void)
{
FILE *f,*outf;
char s[100];
struct node *tree=NULL;
if ( (f=fopen("test.txt","r")) == NULL )
{
printf("Unable to open test.txt\n");
system("PAUSE");
}
else
{
while ( fscanf(f,"%99s",s)!= EOF )
{
tree=inserttree(tree, s);
printtree(tree, f);
}
fclose(f);
}
return 0;
}
Does anything jump out at anyone as a problem?
Thanks for the help.