简体   繁体   English

对 STL 字符串使用 fread/fwrite。 这是对的吗?

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

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.所以,我想,我不能使用 fread 和 fwrite 函数从文件中写入和读取这个结构。 Because string may reserve different memory capacity.因为字符串可能会保留不同的 memory 容量。 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?它真的有一些问题吗?

You are justified in doubting this.你有理由怀疑这一点。 You should only stream POD types with fwrite and fread and string is not POD .您应该只 stream POD 类型与fwritefreadstring is not POD

You shouldn't do it like this, because different implementations use different structures of std::string .您不应该这样做,因为不同的实现使用不同的std::string结构。

In general you should only serialize integral types, the boolean type, binary data (if you can call it serializing).一般来说,你应该只序列化整数类型,boolean 类型,二进制数据(如果你可以称之为序列化)。 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.您也必须小心 C/C++ 结构,因为它们可能包含不可预测的填充量。

You should serialize data.您应该序列化数据。

You might like to do this manually - when it comes about std::string , check out:您可能希望手动执行此操作 - 当涉及std::string时,请查看:

When it comes about more complex objects, you might be interested in things like Google Protocol Buffers and/or Thrift .当涉及到更复杂的对象时,您可能会对Google Protocol Buffers 和/或 Thrift 之类的东西感兴趣。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM