读/写联合以在C+&#x2B中文件安全是否安全。 11?

发布于 2025-01-18 07:49:32 字数 1101 浏览 3 评论 0原文

在C ++ 11中,可以安全地将固定的大小结构读取到文件,但是我找不到任何引用是否可以安全地读取/编写一个联合文件。如果有以下结构和联合:

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;
};

在这种情况下,在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?
}

感谢您的帮助!

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!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文