I am playing around with serialization in C. Consider structs that do not contain pointers. Is the in-memory representation of such structs a valid format to be written to and read from disk? More specifically, can I write the bytes of a struct to disk, and then read them back safely?
I have a simple pointer-free struct:
struct point {
float x; float y;
char name[16];
};
Writing the struct:
// Get the raw bytes of a struct
struct point p = {4.2, 2.718, "p1"};
uint8_t *raw_p = (uint8_t *)&p;
// Write them to a file
FILE *f = fopen("tmpfile", "wb");
fwrite(raw_p, sizeof(struct point), 1, f);
fclose(f);
Reading the struct back:
// Read the file into a buffer
FILE *f = fopen("tmpfile", "rb");
uint8_t buf[128] = {0};
fread(buf, sizeof(struct point), 1, f);
// Try to convert the bytes to a struct
struct point p = *(struct point *)buf;
printf("point {x: %f, y: %f, name: %s }n", p.x, p.y, p.name);
fclose(f);
Is this code safe? Is it correct? I am interested in the issues with this approach. Specifically, where does this code fail in terms of portability? Additionally, is this the most performant way to serialize a simple struct?
joe is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.