2012-05-17 59 views
2

我有下面的代碼,像這樣寫到結構到一個文件:FREAD不讀書結構

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

用於分配我的結構定義是這樣的:

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

那麼,什麼導致我的程序掛起?

回答

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定義,但我認爲你在寫()

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

是的,你是對的,你的答案的第二部分。 – Dean

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個字節。