4

I have a structure, that contain string. Something like that:

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

So, i suppose, that i cannot write and read this structure from file using fread and fwrite functions. Because string may reserve different memory capacity. But such code works correctly.

Chunk var;

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

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

Is there really some problems in it?

pmg
  • 106,608
  • 13
  • 126
  • 198
Vera
  • 135
  • 3
  • 7

3 Answers3

8

You are justified in doubting this. You should only stream POD types with fwrite and fread and string is not POD.

David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490
2

You shouldn't do it like this, because different implementations use different structures of std::string.

In general you should only serialize integral types, the boolean type, binary data (if you can call it serializing). Make sure to use one endian-ness if you are thinking of sharing serialized data between platforms.

Watch out with floats, doubles and pointers. They can become very pesky.

You'll have to watch out with C/C++ structs too ebcause they can contain unpredictable amounts of padding.

orlp
  • 112,504
  • 36
  • 218
  • 315
  • Even structs are a problem because they contain unpredictable amounts of padding. It may be OK if you read the data in the same program and process that you're writing it in, but that's definitely not portable. You really have to serialize struct members individually, recursively. – Kerrek SB Jul 21 '11 at 21:20
0

You should serialize data.

You might like to do this manually - when it comes about std::string , check out:

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

Community
  • 1
  • 1
Grzegorz Wierzowiecki
  • 10,545
  • 9
  • 50
  • 88