2014-02-08 56 views
0

我有這個函數返回一個指向這個函數內已分配書籍的指針,並且這個數據來自一個名爲book_saved.dat的文件。我可以編譯這段代碼,但它會給我發垃圾,爲什麼?讀取一個文件並返回一個指針C

book_saved是一個已經存在

*我在我的原代碼結構的文件。

#include <stdio.h> 
#include <stdlib.h> 


book_t *book_load(){ 

    book_t *book;// book_t is a struct 

    book = (book_t*)malloc(sizeof(book_t)); 

    if (book == NULL) 
     exit(1); 

    FILE*fp = fopen ("book_saved.dat", "rb"); 

    fread (book, sizeof(book_t), 1, fp); 

    return book; 

} 

void print_book (book_t *book) { 

    printf("\n"); 
    printf ("Book \nTitle: %s\nWriter: %s\nPublishing: %s\nYear: %d\nWeight %.1f\n", book->title, book->writer, book->publishing_house, book->year, book->weight); 

} 

int main (int argc, char *argv[]){ 

    book_t *pontaux = book_load(); 
    print_book (pontaux); 

    free (pontaux); 


    return 0; 
} 
+0

'book_saved.dat'文件來自哪裏?您是使用其他程序製作的,還是使用文本編輯器手動輸入的? – dasblinkenlight

+0

我做了一個寫而不是讀的程序。 – Kay

+1

是否是book_t char指針或數組的成員? –

回答

0

你能提供你的寫作功能嗎?我做了一個相當基本的,它似乎正常工作。我建議將struct粘貼到共享頭文件中,以確保所使用的結構完全相同,並在十六進制編輯器中打開book_saved.dat以確保其中的格式正確。

#include <stdio.h> 
#include <stdlib.h> 
#include <string.h> 

typedef struct book_t { 
    char title[75]; 
    char writer [50]; 
    char publishing[30]; 
    int year; 
    float weight; // kg. 
} book_t; 

void book_make(){ 

    book_t *book;// book_t is a struct 

    book = (book_t*)malloc(sizeof(book_t)); 

    if (book == NULL) 
     exit(1); 
    strcpy(book->title, "Harry Potter: World\'s End"); 
    strcpy(book->writer, "JK Rowlingbatman"); 
    strcpy(book->publishing, "Publisherguy inc."); 
    book->year = 3000; 
    book->weight = 14.6; 

    FILE*fp = fopen ("book_saved.dat", "wb"); 

    fwrite(book, sizeof(book_t), 1, fp); 

    fclose(fp); 
} 


book_t *book_load(){ 

    book_t *book;// book_t is a struct 

    book = (book_t*)malloc(sizeof(book_t)); 

    if (book == NULL) 
     exit(1); 

    FILE*fp = fopen ("book_saved.dat", "rb"); 

    fread (book, sizeof(book_t), 1, fp); 

    return book; 

} 

void print_book (book_t *book) { 

    printf("\n"); 
    printf ("Book \nTitle: %s\nWriter: %s\nPublishing: %s\nYear: %d\nWeight %.1f\n", book->title, book->writer, book->publishing, book->year, book->weight); 

} 

int main (int argc, char *argv[]){ 

    book_make(); 
    book_t *pontaux = book_load(); 
    print_book (pontaux); 

    free (pontaux); 


    return 0; 
} 
+0

謝謝!我的寫作功能是錯誤的,我把一個'&'在fwrite x) – Kay

+0

我總是用指針犯錯誤... – Kay

+0

沒問題!它發生在我們最好的人身上。除了更多的代碼之外,我不能給出太多建議,或者切換到更好的類型安全的語言 – cactus1