我写了一个程序来创建一个简单的字典。我想将字典数据保存到文件中,下次运行程序时,我希望将该数据加载到链接列表中。
这是我的代码:
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);
}
但是,如何读取文件并将数据加载回链表中呢?
最佳答案
您使用了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;
}
关于c - C:将数据从文件加载到链接列表,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/44253842/