2014-01-22 82 views
1

好吧,所以这里是我的问题我想弄清楚如何编写我的单链表到文件,不知道应该怎么用,所以我去了txt文件和fprintf不知道如果如果有人能够说出哪种方式会更好,解释会更好,那该多好。那么回到我的代码我有问题保存到文件基本上我的函数为第一个客户端保存项目,但不保存第二个项目。我做错了什么?如果我的代码的其余部分是必要的我可以发布它,但它像500行。保存到txt文件链接列表

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; 
} 
+0

错误?问题? –

+0

那么没有错误,就像我说它保存客户端列表,但第二个客户端的内部列表没有保存 – user3209183

回答

1

您需要在外部while循环的最后更新CurrentItem,你设置新head后:

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

否则,CURRENTITEM用来扫描物品的清单第一个客户端,然后永远不会重置到下一个客户端的项目的开始。

编辑

它实际上是更好的while循环的开始设置CurrentItem,否则当head为NULL CurrentItem = head->item_data会失败:

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

当我添加这个部分时,我的函数在第一次循环后崩溃。你确定当我开始设置struct item * CurrentItem = head-> item_data;可以像这样更新它? – user3209183

+0

当然。检查head-> item_data是否在列表末尾正确设置为NULL,然后使用'gdb'。另外,发布一个包含一些数据的完整示例以重现问题。 – lbolla

+0

啊,显然如果'head'为NULL'CurrentItem'将尝试访问一个NULL指针。所以你最好在while循环的开始处移动CurrentItem。 – lbolla