I need to write a vector to a file, and then read it back into a vector.
The vector contains hundreds, possibly thousands, of structs which each contain 2 different structs.
I thought that the best way to do it would be to get the pointer with MyVector.data() and somehow write the data using that.
Just in case here's a diagram of the vector:
MyVector
- Struct 1
- Struct A
- float
- float
- bool
...
- Struct B
- float
- float
- bool
...
- Struct 2
- Struct A
- float
- float
- bool
...
- Struct B
- float
- float
- bool
...
and so on.
I tried multiple methods, such as ofstream.write() and fwrite(), but none of them worked.
void PosBot::SaveMacro(std::string macroName) {
int val = _mkdir("PosBot");
std::string a = "PosBot/" + macroName + ".pbor";
std::ofstream outfile(a.c_str(), std::ios_base::binary);
std::copy(Frames.begin(), Frames.end(), std::ostreambuf_iterator<char>(outfile));
outfile.close();
}
void PosBot::LoadMacro(std::string macroName) {
Frames.clear();
Checkpoints.clear();
CheckpointFrames.clear();
std::string a = "PosBot/" + macroName + ".pbor";
std::ifstream infile(a.c_str(), std::ios_base::binary);
std::istreambuf_iterator<char> iter(infile);
std::copy(iter, std::istreambuf_iterator<char>(), std::back_inserter(Frames)); // this leaves newVector empty
infile.close();
}
This gives me an error of:
binary '=': no operator found which takes a right-hand operand of type 'Frame' (or there is no acceptable conversion)
std::ostreambuf_iteratorwrites character data to the output stream whenever it is assigned a single character via itsoperator=. Since you are specifyingcharas theCharTtemplate parameter ofstd::ostreambuf_iterator, itsoperator=expects acharvalue to be assigned to it (ie, when used to write data from astd::vector<char>,std::string, etc), but you are trying to writeFrameobjects from astd::vector<Frame>instead. IOW, since you are trying to writeFrameobjects wherecharvalues are expected, that is why you are getting the conversion error onoperator=.You have a similar issue with reading in using
std::istreambuf_iterator, too. It is meant for reading in character data (via itsoperator*), not structured data.For what you are attempting to do, you need to use
std::ostream_iterator(andstd::istream_iterator) instead. You will simply have to define an overloadedoperator<<(andoperator>>) forFrameto write/read its member data to/from astd::ostream/std::istreamas needed.Try this: