I'm in the second semester of my college so I just started coding. Recently we learned something about binary trees. So I just wanted to code my own ones. I decided to code a binary tree contact book.
First I'm saving my struct into a .txt file. (I want it in a txt file, not a binary, because then i can read it after the program.) After that I try to load it again in a node to rebuild my binary tree.
Here we go with a shortened version. I commented the important parts.
#define CLEN 100
struct binarytree {
struct binarytree *left;
struct binarytree *right;
char *firstname;
char *lastname;
char *city;
char *street;
char *addr;
char *tel;
} typedef btree;
//-----------------------------------------
btree *creatnullnode(void);
btree *loadtree(char *filename);
//-----------------------------------------
btree *creatnullnode(void) {
btree *node = malloc(sizeof(btree));
node->left = NULL;
node->right = NULL;
//TODO: the memmory is not right allocated..
node->firstname = (char*)malloc(CLEN * sizeof(char));
node->lastname = (char*)malloc(CLEN * sizeof(char));
node->city = (char*)malloc(CLEN * sizeof(char));
node->street = (char*)malloc(CLEN * sizeof(char));
node->addr = (char*)malloc(CLEN * sizeof(char));
node->tel = (char*)malloc(CLEN * sizeof(char));
return node;
}
btree *loadtree(char *filename) {
FILE *fp;
btree *tree = NULL;
btree *node = creatnullnode();
char ch = "";
int lines = 0;
fp = fopen(filename,"r");
if (!fp) {
printf("Error. no file\n");
return NULL;
} else {
while (!feof(fp)) {
ch = fgetc(fp);
if (ch == '\n')
lines++;
}
fseek(fp, 0,(int)lines % 2);
//TODO: right here the memory of every char can't be read anymore
fscanf(fp, "%s\t\t%s\t\t\t%s\t%s\t\t%s\t\t%s\n",
&node->firstname, &node->lastname, &node->addr, &node->city,
&node->street, &node->tel);
tree = insertnode(tree, node);
fseek(fp, 0, 0);
//rekursiveload(&tree, fp); //TODO: - ausprogrammieren -
}
fclose(fp);
return tree;
}
While debugging I saw that the memory did not get correctly allocated. But i don't know how to fix it.
after allocationg the char[] is set to: node->firstname = 0x007db250
"ÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍýýýýM¸Þµ¦æ"
Debugger says: <Error reading the characters of the string.>
after fscanf