【问题标题】:Read binary file to struct array pointer读取二进制文件以构造数组指针
【发布时间】: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


【解决方案1】:

Product *shop; 在这里,您声明了一个指针,但您没有为它分配内存。您应该使用malloc() 进行分配或进行一些静态分配。

要知道文件中结构的数量,我会寻找到文件的末尾,计算字节数并除以结构的大小。

【讨论】:

    【解决方案2】:

    附注:您不需要jees 变量。只需在 编写后测试中断条件并显式中断循环:

        for (i = 0; ; i++)
        {
            fwrite(&shop[i], sizeof (Product), 1, OUT);
    
            if (shop[i].name[0] == '\0')
                break;
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-10-30
      • 1970-01-01
      • 1970-01-01
      • 2019-10-02
      • 2012-12-25
      • 1970-01-01
      • 1970-01-01
      • 2020-11-24
      相关资源
      最近更新 更多