我想知道你是否可以帮助我,我真的坚持我写的代码。我应该预先从以下列方式构造的文件中填充树。
Hello
goodbye
yes
' ' <- This is an actual space in the file
no
end of file
当有空间时,我想回到之前的节点并向右走,并在它到达EOF时返回。 因此,上述文本将按以下方式构建
hello
goodbye null no right child
yes no
这个函数应该预先填充我的树。我在这里使用我的readFile函数抓取数据
char *readFile(FILE *fp)
{
int c = 0;
int i = 0;
size_t capacity = 10;
char *arr = NULL;
char* temp = NULL;
arr = (char*) malloc(capacity * sizeof(char));
while (((c = fgetc(fp)) != '\n') && (c != EOF))
{
if(capacity == (i+2))
{
capacity *= 2 ;
temp = (char*)realloc(arr,capacity * sizeof(char));
/*Assigns Address to newly allocated array*/
arr = temp;
}
arr[i] = c;
i++;
}
arr[i-1] = '\0';
if(arr[0] == '\r') /* Line spaces to move up*/
{
printf("Got here SPACE\n");
arr[0] = ' ';
}
else if(c == EOF)/*if its an end of file return*/
{
printf("Got here EOF \n");
arr[0] = ' ';
}
return arr;
}
我填充树的递归算法称为populate。我在递归时并不是那么出色,但是我已经多次走过我的代码而且看不出什么是明显错误的。目前似乎我只能打印根。试图读取左或右根数据给我一个直接的seg错误
void populate(FILE *fp,struct node *root)
{
char *data = readFile(fp);
if(data[0] == ' ') /*possible issues with usingn null charater? */ /*statement is true for both EOF and spaces*/
{
return;
}
printf("Creating Node\n");
if(root == NULL)
{
root = createNode();/* create the current root */
root->data = data;/*assign data*/
}
printf("%s\n",data);
populate(fp,root->left);
populate(fp,root->right);
}
我的主要
int main(int argc, char *argv[])
{
FILE *fp;
node *root = createNode();
fp = fopen("qa.db","r+");
if(fp == NULL)
{
printf("File not open");
}
populate(fp,root);
if(root == NULL){
printf("Equal to NULL\n");
}
printTree(root);
/*check = checkFile(fp)*/
fclose(fp);
return 0;