Hallo!
I've been having some trouble getting a save/load function to work properly. I'm trying to save object and their properties to a file in binary using fstream. And then being able to load the object from the binary file the next time im running my project.
Quick breakdown: I got this class CMapMgr which holds a vector of CMap instances, and each CMap instance holds a vector with CTile instances.
So when everything is initiated and running, and when i run this code, how much is saved?
// mFile is of fstream type and is a private member.
// mapList is the name of the CMapMgr's vector, with each element holding a CMap instance.
bool CMapMgr::save(std::string filename) {
/** Load the file for binary output */
mFile.open(filename.c_str(), std::ios::out | std::ios::binary);
// Would it be useful to save length of the vector in it's current state? Or perhaps
// It's possible to tell the loading func the # of maps in any other way?
int i=0;
/** iterate through maps and save each one */
for (std::vector<CMap>::iterator map = mapList.begin(); map!=mapList.end(); ++map) {
if (mFile.write((char*)&map, sizeof(CMap))) { //Pass data to the file
log_debug("MapMgr->save: saved %s as %i map", mapList[i].mMapName.c_str(), i);
i++;
}
else {
log_error("MapMgr->: failed to save %s", mapList[i].mMapName.c_str());
return false;
}
}
mFile.close();
return true;
}
**I might doing something wrong in my iteration too, dont have all that much knowledge about iterations.
Question 1: So, when I first saves this and then trying to read from it. Do I need to save the length of the vector to be able to iterate through and load later. Or is it possible to try read a map object from the file and on fail, stop loading maps? Or could it result in a "faulty object"? Now when i try to load i use about the same way as saving, only reading instead of writing. Should do the trick?
Question 2: When i write this to the file, does it mean the instances of an instance gets written to file? As each CMapMgr vector index holds a instance of CMap which should hold seveal CTiles instances.
Would greatly appreciate some hints on this one! Sorry for my lack of terminology & probably grammar aswell. And I hope my questions arent too diffuse. I'm not after code hints (well maybe some), but more a explanation of how it works to write/read objects from file.
Thanks ~ R