[英]Write struct to file
When I write a struct to file, how the memory sets up in the file? 当我向文件写入结构时,如何在文件中设置内存? For instance this struct and function: 例如,以下结构和功能:
struct vector3D
{
public:
float x, y, z;
vector3D(float modelX, float modelY, float modelZ)
{
x = modelX;
y = modelY;
z = modelZ;
}
vector3D()
{
x = 0;
y = 0;
z = 0;
}
}
inline void writeVector3D(vector3D vec, FILE *f)
{
fwrite((void*)(&vec), sizeof(vector3D), 1, f);
}
And this code in main: 这段代码在main中:
vector3D vec(1, 2, 3);
writeVector3D(vec, file);
How does the information sets up in the file? 文件中的信息如何设置? does it like 123
? 像123
吗? Or struct has different set up? 还是struct有不同的设置?
You probably need to read about: 您可能需要阅读以下内容:
Data will be written in same order as they are placed in memory, including alignment gaps. 数据将按照它们在内存中的写入顺序进行写入,包括对齐间隙。
It writes it as a sequential binary stream. 它将其写入为顺序二进制流。
The size of the file will be the size of the struct . 文件的大小将为struct的大小 。
In your case, it would write a total of 12 bytes (4 bytes per float), and it will be structured this way: 在您的情况下,它将总共写入12个字节(每个浮点数4个字节),并且将采用以下方式进行结构化:
You need to have preprocessor #pragma pack(1) to byte align the structure otherwise its aligned depending on the processor architecture(32-bit or 64-bit). 您需要具有预处理器#pragma pack(1)以字节对齐结构,否则根据处理器体系结构(32位或64位)对其进行对齐。 Also check this #pragma pack effect 还要检查此#pragma pack效果
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.