0

I would like to write a struct to a file as binary. The struct has two members, one is POD-only but the problem is the second member is a string:

struct ToWrite
{
    std::string _str;
    PODType _pod;
};

If I was simply writing the POD type as binary I would do:

file.write((char*)&_pod, sizeof(_pod));

and to read back:

const PODType& pod = *reinterpret_cast<const PODType*>(&bytes[position]);

However, I'm aware the string is more-complicated because you need to record the size. If I were to add a third class member, being an int containing the size of the string, how do you write and read the struct?

user997112
  • 29,025
  • 43
  • 182
  • 361
  • Whilst that question is similar, it is more specific to a particular scenario and my question is more general and simpler. – user997112 Jun 21 '19 at 17:46
  • *being an int containing the size of the string* -- Why? A `std::string` knows its size already by utilizing the `size()` member function. Why introduce extraneous and superfluous variables? All that does is to increase the chance for bugs to occur. – PaulMcKenzie Jun 21 '19 at 17:55

1 Answers1

1

You need to do three things:

  1. Define a storage format for the structure as a stream of bytes.
  2. Write code to convert the structure into an array of bytes in the format you defined in step 1.
  3. Write code to parse the array of bytes you defined in step 1 and fill in the structure.

If you want to find more information, the best search keyword to use is probably "serialization". There are lots of serialization libraries that you can use to save you from having to go through this complexity every time you need to serialize/deserialize a data structure. I personally like protocol buffers and boost serialization, but there are lots of options.

David Schwartz
  • 179,497
  • 17
  • 214
  • 278