简体   繁体   English

如何在文件中写入一个包含 Malloc 数组的结构

[英]how to write in a file a struct that has an array with Malloc

I try to print in a file the content of a structure that has a dynamic array inside and I think I'm not getting it我尝试在文件中打印内部具有动态数组的结构的内容,但我想我没有得到它

the struct looks like结构看起来像

struct save {
    char s_ext[5];
    char *s_bits;
    long s_frec[256];
    long int s_sim;
};

here I save the imformation in the struct在这里我将信息保存在结构中

struct save *res = malloc(sizeof(struct save));

I try to malloc the array s_bits inside a struct我尝试 malloc 结构中的数组 s_bits


    res->s_bits = malloc(sizeof(char) * sim);

    if (res->s_bits == NULL) {
        printf("error\n");
    }

    strcpy(res->s_bits, textDeco);
    strcpy(res->s_ext, extension);
    res->s_sim = sim;

    for (i = 0; i < 15; ++i) {
        printf("%ld -> %d:%d, ", i, res->s_bits[i], textDeco[i]);
    }
    printf("\n");
    for (i = 0; i < 256; ++i) {
        res->s_frec[i] = frecCopy[i];
    }

open the file打开文件

FILE *save_struct = fopen("codi.dat", "w");

When I try to write the struct on a binary file using fwrite当我尝试使用 fwrite 在二进制文件上写入结构时


if (fwrite(res, sizeof(struct save), 1, save_struct) != 0) {
        printf("file created!\n");
    } else {
        printf("error\n");
    }

it doesn't write a the elements of s_bits, which I don't want.它不写我不想要的 s_bits 的元素。

how do i get the elements with fread?我如何使用 fread 获取元素?

You allocate your struct like this:你分配你的结构是这样的:

struct save *res = malloc(sizeof(struct *res));
if(!res) // handle errror
res->s_bits =  malloc(sim);
if(!res->s_bits) // handle error

When you use fwrite() to store the struct to a file, it will save pointer value res->s_bits but not the array it points to.当您使用fwrite()将结构存储到文件时,它将保存指针值 res->s_bits 但不保存它指向的数组。 The way to handle that is write out each field individually.处理的方法是单独写出每个字段。 When this gets annoying find a library to help you serialize your data (Cap'n Proto, protobuf, JSON etc).当这变得烦人时,找到一个库来帮助您序列化数据(Cap'n Proto、protobuf、JSON 等)。 You should also consider SQLite.您还应该考虑 SQLite。

As you only have one field like this you could make s_bits a flexible array member:因为你只有一个这样的字段,你可以使s_bits成为一个灵活的数组成员:

struct save {
    char s_ext[5];
    long s_frec[256];
    long int s_sim;
    char s_bits[];
};

and now you allocate it like this:现在你这样分配它:

struct save *res = malloc(sizeof(struct *res) + sim);

and you would write it in a similar fashion:你会以类似的方式编写它:

fwrite(res, sizeof(*res) + res->s_sim, 1, save_struct)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM