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

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-07 08:42:47

问题


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?


回答1:


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




回答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.




回答3:


You should serialize data.

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

  • const charT* std::string::c_str() const
  • const charT* std::string::data() const

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



来源:https://stackoverflow.com/questions/6782632/using-fread-fwrite-for-stl-string-is-it-correct

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!