对 STL 字符串使用 fread/fwrite。正确吗?
我有一个包含字符串的结构。像这样的东西:
struct Chunk { 整数a; 字符串 b; 整数c; 因此
,我想我无法使用 fread 和 fwrite 函数从文件中写入和读取此结构。因为字符串可能保留不同的内存容量。 但这样的代码可以正常工作。
Chunk var;
fwrite(&var, sizeof(Chunk), 1, file);
fread(&var, sizeof(Chunk), 1, file );
这里面真的有问题吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
你有理由怀疑这一点。您应该仅使用
fwrite
和fread
流式传输 POD 类型,并且string
不是POD
。You are justified in doubting this. You should only stream POD types with
fwrite
andfread
andstring
is notPOD
.您不应该这样做,因为不同的实现使用不同的
std::string
结构。一般来说,你应该只序列化整型、布尔类型、二进制数据(如果你可以称之为序列化)。如果您考虑在平台之间共享序列化数据,请确保使用一种字节序。
小心浮点数、双精度数和指针。他们会变得非常讨厌。
您也必须注意 C/C++ 结构,因为它们可能包含不可预测的填充量。
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.
您应该序列化数据。
您可能想手动执行此操作 - 当涉及
std::string
时,请查看:const charT* std::string::c_str() const
const charT* std::string::data() const
当涉及到更复杂的对象时,您可能会对 Google Protocol Buffers 和/或 Thrift 之类的东西。
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.