读/写联合以在C+&#x2B中文件安全是否安全。 11?
在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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论