简体   繁体   中英

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:

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 structure alignment ( http://en.wikipedia.org/wiki/Data_structure_alignment ) - for information about how struct members are arranged in memory
  • Endianness ( Endianness ) - for information about how single variable arranged in memory
  • Floating-point representation in memory (can't add third link) - because floating-point variables is much more 'strange' than integer ones.

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:

  • First 4 bytes would represent the float 1
  • Second 4 bytes would represent the float 2
  • Third 4 bytes would represent the float 3

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM