It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center
                            
                        
                    
                
                                7年前关闭。
            
                    
此代码应该“打开”输入的已保存的txt文件,并且用户可以对其进行编辑...

例如,我在save.txt中保存了“ Bob 12345 17”和“ Max 123456 18” ...当我打开文件文件并在链接列表中全部打印时,它仅显示:“ Max 123456 18” ...并且每当我关闭程序并尝试先打开save.txt而不覆盖它时,当我在链接列表中打印所有内容时,它什么都不显示...

FILE* open;
char filenameopen[100];

printf ("\nType the name of the file you want to open: ");
scanf ("%s", filenameopen);
printf ("\n");

open = fopen (filenameopen, "r");
if (filenameopen == NULL)
    printf ("No such file exists\n\n");
else
{
    phonebook_t *openentry = (phonebook_t*) malloc (sizeof(phonebook_t));
    openentry = head;

    while (1)
    {
        fscanf (open, "%s %s %d", openentry -> name, openentry -> tel, &openentry -> age);
        if (feof (open))
        {
            openentry -> next = NULL;
            break;
        }
        openentry -> next = (phonebook_t*) malloc (sizeof(phonebook_t));
        openentry = openentry -> next;
    }

    fclose(open);
}

最佳答案

看起来在while循环中,当您将链接列表的标题分配给下一个节点时,它会丢失标题的头...因此,一旦完成,您将无法打印整个列表与循环。

将您的代码调整为如下所示:

//declare you head-pointer outside the scope of the if-statement
phonebook_t *ll_head = (phonebook_t*) malloc (sizeof(phonebook_t));

if (...)
{
    //...
}
else
{
    //assign a temporary pointer to use in your while-loop
    phonebook_t* openentry = ll_head;

    //...rest of your code
}


现在,当您完成while循环时,从ll_head开始打印,因为它仍指向链接列表的开始,而不是最后一个节点。

关于c - 请告诉我我的错误,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/12621687/

10-11 22:32
查看更多