c - 保存到txt文件链表

标签 c file linked-list

好的,这就是我的问题 我正在尝试弄清楚如何将我的单链表写入文件,但还不确定我应该使用什么,所以我使用了 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/

相关文章:

iphone - 在C中跨步复制内存的最快方法?

java - String类内部是什么?

c - 使用单一光源渲染 3D 立方体的最简单方法是什么?

eclipse - 如何在 Eclipse 导航器/资源管理器中显示所有文件?

java - 覆盖通过 FileDescriptor FD 获取的 FileOutputStream 中的属性文件

c - 从 C 中的文件行中提取信息

c - 我应该使用哪种类型的函数?

c - 使用双指针将字符串转换为链表

C、 Camel 文转蛇文

c - Gtk3 - 如何在它的容器中获取小部件的索引?