恐惧不读结构

时间:2012-05-17 00:03:36

标签: c

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

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;

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

2 个答案:

答案 0 :(得分:3)

你需要对结构和指针进行复习。

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);

可能还有其他问题,但这应该让你开始。

你应该包括用于赋值的stuct定义,但我认为你在write()中有同样的问题

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

答案 1 :(得分:3)

我猜这个问题是读到一个未初始化的指针。您没有为assignment分配内存。你可能想要更像这样的东西:

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);
    }

另请注意,您的原始代码需要sizeof(assignment),这在宣布为Assignment* assignment;时无法达到预期效果。它将为您提供Assignment*的大小,这是任何其他指针的大小 - 32位系统上的4个字节,或64位上的8个字节。