Using fread / fwrite for an STL string. Is it correct?

I have a structure containing a string. Something like that:

struct Chunk { int a; string b; int c; };

So, I suppose that I cannot write and read this structure from a file using the fread and fwrite functions. Because the line can reserve different memory capacity. But such code works correctly.

Chunk var;

fwrite(&var, sizeof(Chunk), 1, file);

fread(&var, sizeof(Chunk), 1, file);

Are there any problems in it?

+4
source share
3 answers

You have the right to doubt it. You should only pass POD types with fwrite and fread and string not POD .

+8
source

You should not do it this way because different implementations use different std::string structures.

In general, you should only serialize integral types, logical type, binary data (if you can call it serialization). Remember to use one endian-ness if you are thinking about sharing serialized data between platforms.

Watch out for floats, doubles and pointers. They can become very annoying.

You will have to keep an eye on C / C ++ structures too, because they can contain an unpredictable amount of additions.

+2
source

You must serialize the data.

You may need to do this manually - when it comes to std::string , check:

When it comes to more complex objects, you might be interested in things like Google Protocol Buffers and / or Thrift .

0
source

All Articles