C:将数据从文件加载到链表

时间:2017-05-30 05:07:28

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

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

这是我的代码:

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);
}

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

2 个答案:

答案 0 :(得分: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;
}

答案 1 :(得分:-1)

为了你必须:

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

2)对于每一行readed,你必须将它添加到你的列表中,例如:

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

缓冲区包含你的行,last是指向列表最后一个元素的指针。