gpt4 book ai didi

C、从文件创建单向链表

转载 作者:行者123 更新时间:2023-11-30 17:50:28 24 4
gpt4 key购买 nike

成功了。我只是愚蠢,在一个地方写了 = 而不是 == t.t 谢谢大家。

我有包含数据的文件,现在我想读取它并将其放入列表中。我不完全知道该怎么做,因为我必须在不久的将来完成这个项目,所以我只是向你寻求帮助;]

头文件:

typedef struct
{
char category[50];
char name[50];
char ingredients[50];
char instruction[1000];
}recipe_t;



typedef struct element
{
struct element *next;
recipe_t recipe;

} el_list;

void all_recipe_list();
void show_all_list(el_list *list);
void add_new_element_to_list(el_list *list, recipe_t formula);

我的列表函数文件:

void all_recipe_list() //reading all record into list + show it(show_all_list function)
{
FILE *database;
recipe_t formula;
el_list *head;

head = NULL;

database = fopen(filename, "rb");
fgetc(database); // function feof returns value only if we read something before, so in order to check if its end, we try to read one char
// when writing data to file, I put \n always before new record
while (!feof(database))
{
fread(&formula, sizeof(recipe_t),1,database);

if (head == NULL)
{
head = malloc(sizeof(el_list));
head->recipe = formula;
head->next = NULL;
}
else
{
add_new_element_to_list(head,formula);
}

fgetc(database); // same as above
}
fclose(database);


show_all_list(head);

}


void show_all_list(el_list *list)
{
el_list *p=list;

while (p != NULL)
{
printf("Kategoria:%s\n", p->recipe.category);
printf("Nazwa:%s\n", p->recipe.name);
printf("Skaldniki:%s\n", p->recipe.ingredients);
printf("Instrukcja:%s\n", p->recipe.instruction);

p = p->next;
}
}

void add_new_element_to_list(el_list *list, recipe_t formula)
{
el_list *p, *new_el;

p = list;
while (p->next != NULL)
{
p = p->next;
}

new_el = malloc(sizeof(el_list));
new_el->recipe = formula;
new_el->next = NULL;
p->next= new_el;
}

存在哪些问题?程序编译正常,但在调用 all_recipe_list 时崩溃。add_new_element_to_list 可能有问题。但无法弄清楚是什么。另外我不知道在 show_all_list p->recipe.category 中是否是正确的方法。

最佳答案

add_new_element_to_list() 中这一行:

new_el->recipe;

应阅读:

new_el->recipe = recipe;

我认为。

关于C、从文件创建单向链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17261610/

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