【发布时间】: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