【发布时间】:2021-03-22 12:27:24
【问题描述】:
我已使用此函数将结构数组写入二进制文件:
int write_binary(const char* filename, const Product* shop)
{
FILE* OUT;
int jees = 0;
int i = 0;
OUT = fopen(filename, "wb");
if (!OUT) {
return 1;
}
while (jees == 0)
{
//the last element of the struct array has '\0' as the first char of its name
if (shop[i].name[0] == '\0')
{
jees = 1;
}
fwrite(&shop[i], sizeof (Product), 1, OUT) ;
i++;
}
fclose(OUT);
return 0;
}
现在我想把它读回一个结构数组指针。我试过了:
Product* read_binary(const char* filename)
{
FILE* IN = fopen(filename,"rb");
Product *shop;
for (int i = 0; i < 10; i++) {
fread(&shop[i], sizeof(Product), 1, IN);
}
fclose(IN);
return shop;
}
但这种方式似乎行不通。有没有办法找出二进制数据中有多少个结构?
【问题讨论】:
-
“似乎不起作用”是什么意思?如果您知道文件的大小,是否足以推断出结构的数量?
-
“似乎不起作用”不是问题描述。陈述观察到的行为。陈述预期的行为。编辑问题以提供minimal reproducible example。也就是说,write 函数一直写入到名称为空(第一个字符为零)为止。所以 read 函数可以一直读到名字为空。
-
Cqn 你提供了结构定义吗?结构中的数组是静态的还是指向存储在其他地方的数组的指针?
-
*shop未初始化 - 您需要在读取之前为其分配内存。 -
您的
read_binary使用指针shop,而它的值是不确定的。您需要为其分配一个有效的Product *值,一个指向足够内存以容纳10 个Products。
标签: arrays c binaryfiles