【问题标题】:Saving to txt file linked list保存到txt文件链表
【发布时间】:2014-01-22 14:14:07
【问题描述】:

好的,这是我的问题哪种方式会更好,解释会很棒。回到我的代码,我在保存到文件时遇到问题,基本上我的函数为第一个客户保存项目,但不是为第二个客户保存项目。我做错了什么?如果我的其余代码是必要的,我可以发布它,但它就像 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;
}

【问题讨论】:

  • 嗯,没有错误,就像我说的它保存了客户列表,但没有保存第二个客户的内部列表

标签: c file linked-list


【解决方案1】:

在设置新的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;
    ...
}

【讨论】:

  • 当我添加这部分时,我的函数在第一次循环后崩溃。你确定当我在开始时设置 struct item *CurrentItem = head->item_data;可以这样更新吗?
  • 当然。检查 head->item_data 在列表末尾是否正确设置为 NULL 等,然后使用gdb。另外,发布一个包含一些数据的完整示例来重现问题。
  • 啊,很明显如果head 为NULL CurrentItem 将尝试访问一个NULL 指针。因此,您最好将 CurrentItem 移到 while 循环的开头。
  • 好吧,如果(head != NULL){ CurrentItem = head->item_data; },谢谢你的帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多