【发布时间】:2015-02-24 00:13:06
【问题描述】:
我正在尝试将“产品”类的向量写入文件并将其读回。但是,我在阅读时会加载垃圾。有人可以回顾一下可能出了什么问题吗?或者建议另一种方法。
#include <fstream>
#include <vector>
#include <iostream>
class Product
{
public:
std::string name;
int code;
double price;
};
int
main ()
{
const char *const file_name = "products.bin";
{
std::vector < Product > prod
{
Product {"Honey", 1, 12.34},
Product {"CoffeeBeans", 2, 56.78},
Product {"Cl", 3, 90.12}
};
for (const Product & p:prod)
std::cout << p.name << ' ' << p.code << ' ' << p.price << '\n';
std::ofstream file (file_name, std::ios::binary);
size_t sz = prod.size ();
file.write (reinterpret_cast < const char *>(&sz), sizeof (sz));
file.write (reinterpret_cast < const char *>(&prod[0]), sz * sizeof (prod[0]));
}
{
std::vector < Product > prod;
std::ifstream file (file_name, std::ios::binary);
size_t sz;
file.read (reinterpret_cast < char *>(&sz), sizeof (sz));
prod.resize (sz);
file.read (reinterpret_cast < char *>(&prod[0]), sz * sizeof (prod[0]));
for (const Product & p:prod)
std::cout << p.name << ' ' << p.code << ' ' << p.price << '\n';
}
}
> Blockquote
【问题讨论】:
-
停止将非POD 类型转储到文件中。
Product包含一个std::string成员。这不会轻而易举地进入,尤其是退出该文件。 -
你怎么能写上面的代码,却没有意识到
std::string不能被bin-dumped? ...您是否无意中从其他人那里复制了一些代码? -
reinterpret_cast表示您的代码是错误的,除非您明确知道为什么它实际上是正确的。 -
更明确地说,
std::string会将文本存储在动态分配的内存中(除非它实现了可选的“短字符串优化”,那么可以在内部存储几个字符的字符串)。因此,您正在写出指向在存储Products 的原始向量离开第一个范围并被销毁后仍然无效的文件的指针 - 所有那些std::strings 都是deleted 并且它们是动态的已释放分配的内存。 -
也许考虑不为此使用二进制文件并使用
file << p.name << '\n' << p.code << '\n' << p.price << '\n'之类的文本格式读取/写入您的值?
标签: c++ c++11 file-io stl stdvector