Hi guys,
I want to read a file full of names and put every name in a sorted binary tree.
I managed to read every name and "store" it in the tree, but when I want to print all
names, it doesn't print any of them.
Here's the code:
Code:
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#define MAXLEN 32
static FILE *file;
struct tnode {
char *name;
int count;
struct tnode *left;
struct tnode *right;
};
struct tnode *addtree(struct tnode *, char *);
void treeprint(struct tnode *);
int getname(char *, int);
int main()
{
struct tnode *root;
char name[MAXLEN];
file = fopen("names.txt", "r");
root = NULL;
while(getname(name, MAXLEN) != EOF)
if(isalpha(name[0]))
addtree(root, name);
treeprint(root);
return 0;
}
struct tnode *addtree(struct tnode *p, char *w)
{
int cond;
if(p == NULL) {
p = (struct tnode *) malloc(sizeof(struct tnode));
p -> name = strdup(w);
//printf("%s", p -> name);
p -> count = 1;
p -> left = p -> right = NULL;
} else if((cond = strcmp(w, p -> name)))
p -> count++;
else if(cond < 0)
p -> left = addtree(p -> left, w);
else
p -> right = addtree(p -> right, w);
}
void treeprint(struct tnode *p)
{
if(p != NULL) {
treeprint(p -> left);
printf("%s\n", p -> name);
treeprint(p -> right);
}
}
int getname(char *name, int lim)
{
int c;
char *w = name;
while(--lim > 0 && (c = getc(file)) != EOF && isalpha(c))
*w++ = c;
if(c == EOF) {
ungetc(c, file);
return EOF;
}
*w = '\0';
return name[0];
}
The file is in the attachment.
I hope someone can point out my mistake(s).
greetz