保存/加载结构数组是个好主意吗?
我想知道使用 fstream 加载/保存某种结构类型的数组是否是一个好主意。注意,我说的是加载/保存到二进制文件。我应该加载/保存独立变量(例如 int、float、boolean)而不是结构体吗?我问这个问题的原因是因为我听说结构可能有某种类型的填充,这可能会抵消保存/加载。
I was wondering if it was a good idea to load/save an array of a certain type of structure using fstream. Note, I am talking about loading/saving to a binary file. Should I be loading/saving independent variables such as int, float, boolean rather then a struct? The reason I ask that is because I've heard that a structure might have some type of padding which might offset the save/load.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
结构可能包含填充,它将被写入文件。如果要使用执行写入操作的同一编译器发出的代码在同一平台上读回该文件,那么这没什么大不了的。但是,这很难保证,如果不能保证,通常应该以某种文本格式编写数据,例如 XML、json 或其他格式。
A structure may contain padding, which will be written to the file. This is no big deal if the file is going to be read back on the same platform, using code emitted by the same compiler that did the write. However, this is difficult to guarantee, and if you cannot guarantee it, you should normally write the data in some textual format, such as XML, json or whatever.
如果没有序列化,您的二进制数据将无法跨不同平台(和编译器)移植。因此,如果您需要可移植性,那么您需要先序列化数据,然后再将其作为二进制存储在文件中。
看看这些:
Without serialization, your binary data will not be portable across different platform (and compilers). So if you need portability, then you need to serialize the data before storing it in file as binary.
Have a look at these:
它并没有被弃用(它不是任何正式规范的一部分,应该在哪里弃用它?),但它非常不可移植,并且可能是序列化内容的最糟糕方法。使用 Boost.Serialization 或类似的库。
It's not deprecated (it's not part of any formal spec, where should it be deprecated?), but it's extremely not portable and probably the worst way to go about serialising stuff. Use Boost.Serialization, or a similar library.
正如您在答案中指出的那样,以这种方式编写结构会发生这种情况。如果您希望文件可以跨平台移植,例如在 Linux i686 上写入的文件由 Sparc 上的 Solaris 打开,那么即使写入单个浮点数也不起作用。
尝试将数据写入文本或 XML 等格式,然后对文件进行 zip/tar 压缩以将其制作为一个文档。
As you pointed out in your answer this will happen with writing structs this way. If you want your files to be portable across platforms, e.g. file being written on Linux i686 to opened by Solaris on Sparc then even writing individual float's won't work.
Try writing your data to something like text or XML and then zip/tar the files to make one document of them.
正如尼尔所说,更喜欢数据的文本表示。 XML 格式可能有点过分了。更简单的版本是逗号分隔值 (CSV) 和每个文本行一个值。
As Neil said, prefer textual representation of data. The XML format may be overkill. Simpler versions are Comma Separated Value (CSV) and one value per text line.