0

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?

UdiM
  • 480
  • 3
  • 19
  • 1
    This writes out the binary representation. A downside to doing a binary output is how you handle changes to the data structure (compared to reading/writing text, such as XML or JSON). – crashmstr Jun 25 '14 at 18:11

3 Answers3

2

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.

Victor Istomin
  • 1,107
  • 8
  • 14
1

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
Matias Cicero
  • 25,439
  • 13
  • 82
  • 154
0

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

Community
  • 1
  • 1
dvasanth
  • 1,337
  • 1
  • 9
  • 10