读取二进制文件到结构体数组指针

问题描述

我已使用此函数将结构数组写入二进制文件

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),IN);
    }
    fclose(IN);

    return shop;
}

但这种方式似乎行不通。有没有办法找出二进制数据中有多少结构?

解决方法

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

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

,

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

    for (i = 0; ; i++)
    {
        fwrite(&shop[i],sizeof (Product),1,OUT);

        if (shop[i].name[0] == '\0')
            break;
    }