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:
vector3D vec(1, 2, 3);
writeVector3D(vec, file);
How does the information sets up in the file? does it like 123
? Or struct has different set up?
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 .
In your case, it would write a total of 12 bytes (4 bytes per float), and it will be structured this way:
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). Also check this #pragma pack effect
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.