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?

1
  • 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). Commented Jun 25, 2014 at 18:11

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.