1

In C++11, it safe to read/write a fixed size struct to a file, but I couldn't find any reference about is it safe to read/write a union to file. If have following struct and union:

struct typeA {
  char val[10];
};

struct typeB {
  int val;
};

union u {
  struct typeA a;
  struct typeB b;
};

struct u_wrapper {
  char type[10]; /* indicate which union member is initialized */
  union u;
};

In this case, is it safe to do the following write() and read() operations on struct u_wrapper ?

/* following code are pseudocode */

struct u_wrapper w;
w.u.b.val = 1; /* init b */
strcpy(w.type, "b");

/* write struct w to a file */
write(fd, &w, sizeof(w));      -----> is using sizeof(w) correct?
...

/* get file size from stat() */
...
size_t file_size = st.st_size;

/* read file content to buf */
void *buf = malloc(file_size);
read(fd, buf, file_size);
...

struct u_wrapper *w_read = reinterpret_cast<u_wrapper *>(buf); ----> is this correct and safe?

/* does it guarrantee w_read->b has the correct value? */
if (strncmp(w_read->type, "b", 1) == 0) {
  printf("Value of b: %d\n", w_read->b.val);   ----> will this always works correctly?
}

Thanks for helping!

TOM ZHANG
  • 65
  • 5
  • 1
    the 'explanation' code here https://en.cppreference.com/w/cpp/language/union. Suggests that referring to a union as a whole (as opposed to the separate fields that are overlaid) is the same as referencing the first field. But it only shows it for writing to a union, but I guess reading is the same – pm100 Mar 31 '22 at 21:07
  • Any write of a union or structure will require a byte count, and that should be well defined and consistent as long as you're using the same compiler and system. – Mark Ransom Mar 31 '22 at 21:22
  • Possible duplicate : [memcpy/memmove to a union member, does this set the 'active' member?](https://stackoverflow.com/questions/39763548/memcpy-memmove-to-a-union-member-does-this-set-the-active-member) – François Andrieux Mar 31 '22 at 21:23
  • 2
    You should almost always prefer text files (JSON or XML) to store data. By writing binary data, you can have a lot of problem related to the size of types, endianess, alignment and also handling new version of the file format as you would eventually need extra members or larger arrays. If you really want to save binary data, then try to defined well aligned structures and also `static_assert` size and offset as needed to ensure that your definition actually matches what you think it is. – Phil1970 Mar 31 '22 at 22:42

0 Answers0