简体   繁体   中英

how to write an object that contains a list to a file c++?

I'm having a problem with reading and writing a file in c++. My issue revolves around trying to save an object that has an attribute vector. While debugging, The object appears to be stored correctly but on reading it back, the vector values are 0 but the size of the vector is correct. After doing some research I'm aware that I probably should serialise somewhere. My problem is that I don't know how and all my research leads me to the library boost. Can someone point me in the right direction? Below are snippets of my code.

MyData.h

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

Written to file like this:

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!";

Read like this:

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));
}

In this simple case you don't need boost. The problem is that you are writing the object (which is meaningless) when you should be writing the floats. You will also need to write the number of floats, so that when you read back you know how many to read. Something like this for writing

// 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));

and something like this for reading

// 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));

A vector typically consists of a small struct containing a pointer to a heap-allocated array. strings are similar. Writing the object only writes the struct, not the dynamic data. For that you need to use something like boost serialization . This will represent the data in a form that can be reloaded.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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