从文件读取到链表

时间:2014-01-22 20:19:06

标签: c file linked-list

好的,所以我的问题是我有2个结构,客户端和项目。 Basicaly项是客户端内的嵌套列表。我无法弄清楚如何从文件中读取所有项目并在阅读时将它们链接到客户端。我知道如果只有我有客户端结构并且必须从文件只读客户端才能完成它,但它至少对我来说非常复杂,而我有内部列表。如何在文件中将项目与客户端分开,以便在我阅读它们时重新链接程序将知道输入是什么?我不想这样做,计算每个客户端链接了多少项目以及保存前有多少客户端。这是我的结构和保存功能。

struct item
{
    char item_name[30];
    char item_state[30];
    float item_price;
    char item_status[30];
    float 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)
    {
        fprintf(f,"%s %s\n",head->client_name,head->client_last_name);
        while(CurrentItem != NULL)
        {

            fprintf(f,"%s %s %f %s %f ",CurrentItem->item_name,CurrentItem->item_state,CurrentItem->item_price,CurrentItem->item_status,CurrentItem->item_price_if_not);
            CurrentItem = CurrentItem->next;
        }
        head = head->next;
        if(head != NULL)
{
          CurrentItem = head->item_data;
}
        fprintf(f,"\n\n");
    }
    fclose(f);
    return NULL;
}

2 个答案:

答案 0 :(得分:0)

检查什么是swizzling和unwizzling或序列化反序列化的指针。来自维基百科:

  

指针调配是基于名称或引用的引用转换   定位指针引用。它通常是执行的   在从可重定位目标文件反序列化(加载)期间   磁盘,例如可执行文件或基于指针的数据结构。该   反向操作,用位置无关替换指针   符号或位置,有时被称为未破坏,并且是   序列化期间执行(保存)

基本上,您需要为每个结构添加一个唯一的id,并在存储到磁盘和读取时使用id访问您的struct实例。 查看herehere

答案 1 :(得分:0)

有很多方法。请考虑使用'('')'

您需要一些分隔符或关键字来设置数据。通过使用分隔符封装每个结构,读取可以确定何时开始或完成新的结构级别。

int foo(void) {
  ...
  fputc('(', f);
  while (head != NULL) {
    fputc('(', f);
    fprintf(f, "%s %s\n", head->client_name, head->client_last_name);
    while (CurrentItem != NULL) {
      fputc('(', f);
      fprintf(f, "%s %s %f %s %f ", CurrentItem->item_name,
          CurrentItem->item_state, CurrentItem->item_price,
          CurrentItem->item_status, CurrentItem->item_price_if_not);
      CurrentItem = CurrentItem->next;
      fputc(')', f);
    }
    head = head->next;
    if (head != NULL) {
      CurrentItem = head->item_data;
    }
    fputc(')', f);
    fprintf(f, "\n\n");
  }
  fputc(')', f);
}
相关问题