Serialize and Back
Last updated on
Write a struct to the disk and read it back again. Serialization has alot of gotchas that I don’t attempt to address here. You might want to consider ProtoBuf-C if you are going to be doing anything heavyweight.
This snippet will write struct some_data to the disk, and then read it back again into an instance of some_data.
/* serialize.c */
#include <stdio.h>
#include <stdlib.h>
struct some_data {
int i,j,k;
};
void
serialize(const struct some_data *in) {
FILE *f = fopen("dump.data", "wb");
if(!f) {
printf("Failed to serialize.\n");
return;
}
const unsigned char *data = (const unsigned char *)in;
int count = sizeof(*in);
int i;
for(i = 0; i < count; ++i) {
fprintf(f, "%c", data[i]);
}
fclose(f);
}
void
de_serialize(struct some_data *out) {
FILE *f = fopen("dump.data", "rb");
if(!f) {
printf("Failed to de-serialize.\n");
return;
}
fread(out,sizeof(*out),1,f);
fclose(f);
}
void
output_obj(const struct some_data *o) {
printf("%d, %d, %d\n", o->i, o->j, o->k);
}
int
main() {
/* serialize */
struct some_data data_to_serialize;
data_to_serialize.i = 123;
data_to_serialize.j = 234;
data_to_serialize.k = 345;
serialize(&data_to_serialize);
output_obj(&data_to_serialize);
/* de-serialize */
struct some_data data_to_deserailize;
de_serialize(&data_to_deserailize);
output_obj(&data_to_deserailize);
return 0;
}
Outputs …
123, 234, 345
123, 234, 345
Compile and run with GCC
gcc serialize.c && ./a.out
or Clang
clang serialize.c && ./a.out