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
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
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.
how do i get the elements with fread?
CodePudding user response:
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. 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). You should also consider SQLite.
As you only have one field like this you could make s_bits
a flexible array member:
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)