【问题标题】:C : Load data from file to the linked listC : 从文件加载数据到链表
【发布时间】:2017-10-30 10:23:22
【问题描述】:

我写了一个程序来创建一个简单的字典。我想将字典数据保存到文件中,下次运行程序时,我想将该数据加载到链接列表中。

这是我的代码:

struct node{   //structure for dictionary
    char word[20];
    char meaning[5][100]; //to store max five meanings
    struct node *next;
};

//This is how I'm saving data to the file. I guess it's working, because size of the file increases..

void WriteData(struct node *head)
{
    FILE *fp = fopen("dictionary.data", "wb");
    if(fp == NULL)
    {
        printf("Error opening file..\n");
        return;
    }
    while(head != NULL)
    {
        fwrite(head->word, sizeof(head->word), 1, fp);
        fwrite(head->meaning, sizeof(head->meaning), 1, fp);
        head = head->next;
    }
    fclose(fp);
}

但是如何读取文件并将数据加载回链表?

【问题讨论】:

  • sizeof(head->word)正好是20,也就是单词的长度..
  • 请注意,“\0”字符后面可能有一些额外的数据,其中可能包含一些敏感信息,请注意正确清零字典数据。
  • 怎么做?
  • 如果我使用strlen 而不是sizeof,每个数据块的大小都会不同。那么我如何读取它以将该数据加载回列表中?

标签: c file file-io struct linked-list


【解决方案1】:

你使用了 fwrite() 函数,现在使用 fread() :) 这是一个伪代码。将转换为 C/C++ 和错误处理留给您。

node *head - nullptr;
node **tail = &head;
while (not end of file)
{
  *tail = allocate_and_nullify_memory();
  fread((*tail)->word, size_of_head_word, 1, fp);
  fread((*tail)->meaning, size_of_meaning, 1, fp);
  //Move the insertion point
  tail = &(*tail)->next;
}

【讨论】:

  • 顺便说一句:tail = &tail->next; -->> tail = &(*tail)->next;
  • @joop 是的,当然。谢谢
【解决方案2】:

为了你必须:

1) 使用 fgets/getline/read/fread 函数读取文件;

2) 对于读取的每一行,您必须将其添加到列表中,例如:

while (read(fd, buffer, dim) > 0) {
    struct node* tmp = malloc(sizeof(struct node));
    strncpy(tmp->word, buffer, dim);
    tmp->next = NULL;
    last->next = tmp;
    last = last-> next;
}

其中 buffer 包含您的行,last 是指向列表最后一个元素的指针。

【讨论】:

  • 错了。您有结构成员对齐问题。 std::cout << sizeof(node::meaning) << ", " << sizeof(node::word) << ", " << sizeof(node) <<"\n";500, 20, 528
猜你喜欢
  • 2017-10-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多