c - 如何使用 fread 读取二进制文件?

标签 c arrays pointers

 typedef struct
{
    char*title;
    char* year;
    char* length; //in minutes
} record;

void write(record* list[])
{
    FILE* out=fopen("output.bin","a");
    if(!out)
    {
        printf("error"); exit(1);
    }else
    {
        int i;
        for (i = 0; i < 1024; i++)
        {
            if(list[i]!=NULL)
                fwrite(list[i], sizeof(record), 1, out);
        }
        fclose(out);
    }
}
void read_back()
{
    FILE* input=fopen("output.bin","r");
    if(!input)
    {
        printf("error"); exit(1);
    }else
    {
        record* temp[1024];
        fread(temp,sizeof(record)*1024,1,input);


        fclose(input);
    }

}

如何使用 fread 读取二进制文件?有人可以检查我使用 fwrite 是否正确吗?我希望我的 read_back 方法能够打印结构中的内容(标题、年份等)。

最佳答案

record 结构元素被定义为指针fread 无法隐式分配这些指针。对于 record 结构中的每个元素,应显式读取值,并在通过 malloc 分配内存后分配相关值。

fwrite 只会以这种方式将内存地址写入内存,因为 record 结构体只有指针> 里面。

有两个选项

定义静态数组定义如下

 typedef struct
{
    char title[256];
    char year[4];
    char length[8]; //in minutes
} record;

通过引用一一写入record结构元素。

关于c - 如何使用 fread 读取二进制文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22491962/

相关文章:

c printf函数动态类型确定

c - C 中的 struct termios 未知行为

arrays - 从 Ruby 数组中删除次要项

c - 可以在数组开始之前向后迭代到一个吗

c - Sizeof 指针与它在 printf 中的表示不同?

c++ - 实现一个进度条类

c - 在空指针上调用 free() 时发生段错误

c - K&R 错误 : conflicting method definition

c - 当函数返回 char 数组指针时,Valgrind 会报错

c - 为什么这个链表无限期地打印最后一个元素?