gpt4 book ai didi

c - 保存到txt文件链表

转载 作者:太空宇宙 更新时间:2023-11-04 03:50:14 26 4
gpt4 key购买 nike

好的,这就是我的问题 我正在尝试弄清楚如何将我的单链表写入文件,但还不确定我应该使用什么,所以我使用了 txt 文件和 fprintf 不确定是否有人能告诉我它是否好哪种方式会更好,解释会很棒。回到我的代码,我在保存到文件时遇到问题,基本上我的函数为第一个客户端保存项目,但不为第二个客户端保存项目。我做错了什么?如果我的其余代码是必要的,我可以发布它,但它大约有 500 行。

struct item
{
char item_name[30];
char item_state[30];
double item_price;
char item_status[30];
double item_price_if_not;
struct item *next;
};
struct client
{
char client_name[30];
char client_last_name[30];
struct item *item_data;
struct client *next;
};




void savetxt(struct client *head)
{
FILE *f;
f = fopen("data.txt","w");
if(f == NULL)
{
printf("error");
}
struct item *CurrentItem = head->item_data;
while(head != NULL)
{
printf("try");
fprintf(f,"%s\n",head->client_name);
fprintf(f,"%s\n",head->client_last_name);
while(CurrentItem != NULL)
{
printf("tryitem");
fprintf(f,"%s\n",CurrentItem->item_name);
fprintf(f,"%s\n",CurrentItem->item_state);
fprintf(f,"%fp\n",CurrentItem->item_price);
fprintf(f,"%s\n",CurrentItem->item_status);
fprintf(f,"%fp\n",CurrentItem->item_price_if_not);
CurrentItem = CurrentItem->next;
}
head = head->next;
fprintf(f,"\n\n");
}
fclose(f);
return NULL;
}

最佳答案

在设置新的 head 之后,您需要在外部 while 循环结束时更新 CurrentItem:

...
head = head->next;
CurrentItem = head->item_data;
...

否则,CurrentItem 用于扫描第一个客户端的项目列表,然后永远不会重置为下一个客户端的项目的开头。

编辑

实际上最好在while循环的开头设置CurrentItem,否则当head为NULL时CurrentItem = head->item_data 将失败:

while (head != NULL) {
CurrentItem = head->item_data;
...
}

关于c - 保存到txt文件链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21285301/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com