这段代码应该“打开”输入的保存的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/