gpt4 book ai didi

c - 如何将二进制文件读入C中的结构

转载 作者:行者123 更新时间:2023-12-04 11:27:58 25 4
gpt4 key购买 nike

我有一个名为 的结构产品 我试图从二进制文件中读取以填充此函数:

void reading(FILE *fp){

Product *obuff = malloc(sizeof(Product));
fread(obuff->code, sizeof(obuff->code), 1, fp);
fread(obuff->name, sizeof(obuff->name), 1, fp);
fread(obuff->quantity, sizeof(obuff->quantity), 1, fp);
fread(obuff->price, sizeof(obuff->price), 1, fp);

printf("%s %s %d %.2f\n", obuff.code, obuff.name, obuff.quantity, obuff.price);
}

当我尝试编译时,我收到错误消息,说由于错误的数据类型而无法传递参数。有没有办法从二进制文件中读取结构,或者我只是在这里做错了什么?

结构:
#pragma pack(2)
struct product {
char code[15];
char name[50];
short int quantity;
double price;
};
#pragma pack()

typedef struct product Product;

最佳答案

您必须传递指针才能拥有 fread()读取数据。

void reading(FILE *fp){

Product *obuff = malloc(sizeof(Product));
fread(&obuff->code, sizeof(obuff->code), 1, fp);
fread(&obuff->name, sizeof(obuff->name), 1, fp);
fread(&obuff->quantity, sizeof(obuff->quantity), 1, fp);
fread(&obuff->price, sizeof(obuff->price), 1, fp);

printf("%s %s %d %.2f\n", obuff->code, obuff->name, obuff->quantity, obuff->price);
free(obuff); /* free whatever you allocated after finished using them */
}

关于c - 如何将二进制文件读入C中的结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36002149/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com