c - C 读取文件并返回指针

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

最佳答案

你能提供一下你的写作功能吗?我做了一个相当基本的,它似乎工作正常。我建议将 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;
}

关于c - C 读取文件并返回指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21642274/

相关文章:

c++ - 与使用指针通过引用传递数组混淆

c - time() 和 gettimeofday() 返回不同的秒数

c - 为什么 block 中分配的数组在 block 结束后仍然存在?

c - linux - 串口编程(ASCII 转字节)

c - malloc 调用 realloc,然后崩溃

c - 类型 "char *"和类型 "char[10]"之间的区别

c - NetworkByteOrder 是否与 Big endian 相同?

c++ - C中的结构内存布局

ios - 从 nsdata 获取字节附加额外的垃圾字符

c - 使用远函数指针