在C语言中读取文件并返回指针
我有一个函数,在这个函数中返回一个指向已分配书籍的指针,数据来自一个名为book_saved.dat的文件。我可以编译这段代码,但它会给我带来垃圾,为什么 已保存的图书是一个已存在的文件 *我的原始代码中有这个结构在C语言中读取文件并返回指针,c,pointers,C,Pointers,我有一个函数,在这个函数中返回一个指向已分配书籍的指针,数据来自一个名为book_saved.dat的文件。我可以编译这段代码,但它会给我带来垃圾,为什么 已保存的图书是一个已存在的文件 *我的原始代码中有这个结构 #include <stdio.h> #include <stdlib.h> book_t *book_load(){ book_t *book;// book_t is a struct book = (book_t*)malloc(
#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;
}
你能提供你的写作功能吗?我做了一个相当基本的,它似乎工作正常。我建议将结构粘贴到共享头文件中,以确保使用的结构完全相同,并在十六进制编辑器中打开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;
}
book_saved.dat文件来自哪里?你是用另一个程序生成的,还是用文本编辑器手动输入的?我做了一个写而不是读的程序。是book\t char指针或数组的成员?数组。typedef struct book_t{char title[75];char writer[50];char publishing[30];int year;float weight;//kg.}book_t@Kay如果你把book_t的typedef放在问题中而不仅仅是一个评论,那会有帮助的。谢谢!我的书写功能出错,我在fwrite x中加了一个“&”没问题!这发生在我们最好的人身上。除了编写更多代码或切换到具有更好类型安全性的语言之外,我无法给出更多建议