我目前正在完成我的大学项目,唯一剩下的就是实现分支删除。但代码因此错误而崩溃。
void treeprintprime(tNode* tree) {
FILE* lasttree = fopen("lasttree.txt", "a");
if (tree != NULL) {
fprintf(lasttree, "%d ", tree->key); //error happens here
treeprintprime(tree->right);
treeprintprime(tree->left);
cout << tree->key << " ";
}
fclose(lasttree);
}
void delete_node() {
int key;
FILE* lasttree = fopen("lasttree.txt", "r+");
struct tNode* root = NULL;
while (fscanf(lasttree, "%d", &key) == 1)
{
root = addNode(key, root);
}
printf("What element and his subtree do you want to delete? \n");
printf(">> ");
fclose(lasttree);
key = scanfunction();
searchtodeleteNode(key, root);
treeprintprime(root);
freemem(root);
printf("\n");
printf("\n");
}
我已经更改了代码。
最佳答案
函数treeprintprime
是一个递归函数。
它打开一个文件,附加键值,然后递归。如果它是 NULL 节点,则文件被无目的打开。并且只有在递归返回后,才会关闭文件。
因此您打开了多个(相同)文件,直到稍后才将其关闭。
在没有可以尝试的代码的情况下,我建议在附加之前和之后立即打开和关闭文件,例如
void treeprintprime(tNode* tree) {
if (tree != NULL) {
FILE* lasttree = fopen("lasttree.txt", "a"); // move the open function to here
// ** note check result of fopen() **
fprintf(lasttree, "%d ", tree->key);
fclose(lasttree); // move the close function to here
treeprintprime(tree->right);
treeprintprime(tree->left);
cout << tree->key << " "; // note this is C++ in tagged C code
}
}
但更好的是在遍历树之前打开文件,然后关闭它。
关于c - 读取访问中断: tree was 0xAE0A74BF,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56840831/