gpt4 book ai didi

c - 害怕不阅读结构

转载 作者:行者123 更新时间:2023-12-04 11:34:15 24 4
gpt4 key购买 nike

我有以下代码将结构写入文件,如下所示:

void write_assignments_to_file(list* assignments, FILE* file)
{
while (assignments != NULL) {
fwrite(assignments->a, sizeof(assignments->a), 1, file);
assignments = assignments->next;
}
fclose(file);
}

这是写入文件,但是当我再次尝试读取文件时,它挂起我的读取代码,如下所示:

list* read_assignments_from_file(FILE* file)
{
Assignment* assignment;

list* item;
item = NULL;

while ( fread(assignment, sizeof(assignment), 1, file) ) {
printf("Reading an assignment in");
insert(item, assignment);
}

fclose(file);

return item;
}

我的插入方法如下所示:

list* insert(list* assignment_pointer, Assignment* new_assignment)
{
list* ap = assignment_pointer;
if(assignment_pointer != NULL){
while (assignment_pointer->next != NULL) {
assignment_pointer = assignment_pointer -> next;
}
assignment_pointer -> next = (struct list*)malloc(sizeof(list));
assignment_pointer = assignment_pointer -> next;
assignment_pointer -> next = NULL;
assignment_pointer -> a = new_assignment;
return ap;
} else {
assignment_pointer = (list*) malloc (sizeof(list));
assignment_pointer -> next = NULL;
assignment_pointer -> a = new_assignment;
return assignment_pointer;
}
}

我的 Assignment 结构定义如下:

typedef struct Assignment {
char* moduleTitle;
char* moduleId;
char* title;
char* author;
time_t date_set;
time_t date_due;
int weighting;
} Assignment;

那么是什么导致我的程序挂起?

最佳答案

您需要复习一下结构和指针。

Assignment *assignment;
fread(assignment /*which is not set*/, sizeof(assignment) /*probably 4*/, 1, file);

/* Should look more like */
Assignment ass;
fread(&ass, sizeof(ass), 1, file);

可能还有其他问题,但这应该可以帮助您入门。

你可能应该包括分配的结构定义,但我认为你在 write() 中有同样的问题

sizeof(assignments->a); /*size of a pointer not an object*/

关于c - 害怕不阅读结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10628331/

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