gpt4 book ai didi

C : Load data from file to the linked list

转载 作者:行者123 更新时间:2023-11-30 16:45:00 25 4
gpt4 key购买 nike

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

这是我的代码:

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 : Load data from file to the linked list,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44253842/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com