【问题标题】:how to write an object that contains a list to a file c++?如何将包含列表的对象写入文件c ++?
【发布时间】:2021-05-25 02:46:40
【问题描述】:

我在用 C++ 读写文件时遇到问题。我的问题围绕着尝试保存具有属性向量的对象。调试时,对象似乎存储正确,但在读回时,向量值为 0,但向量的大小是正确的。在做了一些研究之后,我知道我可能应该在某个地方进行序列化。我的问题是我不知道我的所有研究如何以及我的所有研究都将我引向图书馆提升。有人可以指出我正确的方向吗?以下是我的代码的 sn-ps。

MyData.h

class MyData { 
public:
std::vector<float> scores;
MyData(vector<float> scores);
MyData(); 
};

这样写到文件中:

MyData mdata(*vector here*);
std::ofstream file_obj("foo.txt");


// Writing the object's data in file
file_obj.write((char*)&mdata, sizeof(mdata));
std::cout << "data saved!";

这样读:

MyData obj;

// Reading from file into object "obj"
file_obj.read((char*)&obj, sizeof(obj));


// Checking till we have the feed
while (!file_obj.eof()) {
    // Checking further
    file_obj.read((char*)&obj, sizeof(obj));
}

【问题讨论】:

  • 首先,你应该以binary模式打开你的文件。其次,写入和读取指向文件的指针是危险的。第三,由于与第二点相关的原因,您的实际数据没有被写入,因为原始对象数据本身仅管理指向堆中内容的指针。写入这些指针不会写入它们指向的数据。阅读对象序列化。
  • 在互联网上搜索“C++ 序列化”。
  • 注明。谢谢你的信息。

标签: c++ file class object vector


【解决方案1】:

在这种简单的情况下,您不需要提升。问题是当您应该编写浮点数时,您正在编写对象(这是没有意义的)。您还需要写入浮点数,以便在您回读时知道要读取多少。像这样写的东西

// how many floats
size_t number_of_floats = scores.size();
// write the number of floats
file_obj.write((char*)&number_of_floats, sizeof(size_t));
// write the floats themselves
file_obj.write((char*)scores.data(), number_of_floats * sizeof(float));

还有类似的阅读方式

// read the number of floats
size_t number_of_floats;
file_obj.read((char*)&number_of_floats, sizeof(size_t));
// adjust vector to correct size for the number of floats
scores.resize(number_of_floats);
// read the floats
file_obj.read((char*)scores.data(), number_of_floats * sizeof(float));

【讨论】:

  • 感谢您提供此解决方案!我不确定编写 vector.data() 是否真的有效。
【解决方案2】:

向量通常由一个包含指向堆分配数组的指针的小结构组成。字符串是相似的。写对象只写结构,不写动态数据。为此,您需要使用boost serialization 之类的东西。这将以可以重新加载的形式表示数据。

【讨论】:

    猜你喜欢
    • 2015-05-17
    • 2013-04-27
    • 1970-01-01
    • 2021-02-27
    • 1970-01-01
    • 2020-07-18
    • 1970-01-01
    • 2017-11-06
    • 1970-01-01
    相关资源
    最近更新 更多