1 year ago

#361092

test-img

TOM ZHANG

Is it safe to Read/Write union to file in C++ 11?

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!

c++

c++11

unions

0 Answers

Your Answer

Accepted video resources