读取文件并在C中返回指针

时间:2014-02-08 05:18:42

标签: c pointers

我有这个函数返回一个指向此函数内已分配的书的指针,数据来自一个名为book_saved.dat的文件。我可以编译这段代码,但它给我发垃圾,为什么?

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

1 个答案:

答案 0 :(得分:0)

你能提供写作功能吗?我做了一个相当基本的,似乎工作正常。我建议将struct放在共享头文件中,以确保使用的结构完全相同,并在十六进制编辑器中打开book_saved.dat以确保格式正确。< / p>

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