Reputation: 23
I have been trying to write this to a file, but to no avail I have found a way, I also need to be able to read from this as well. Here is the struct
struct details
{
float balance=0;
vector<string> history;
string pin;
};
struct customer
{
int vectorID;
string name;
char type;
details detail;
};
vector<customer> accounts;
what I have right now is:
ofstream fileBack;
fileBack.open("file.txt", ios::in|ios::binary|ios::trunc);
fileBack.write(reinterpret_cast<char*>(&accounts), accounts.size()*sizeof(accounts));
fileBack.close();
And I know this is wrong because when I open the file it is not nearly large enough to contain the information I put into it. All help appreciated, thank you in advance
Upvotes: 1
Views: 59
Reputation: 33854
A very easy way is to use Boost Serialization
. You will need to define a member function in each of your classes to handle the serialization for example:
void details::serialize(Archive & ar, const unsigned int version) {
ar & balance;
ar & history;
ar & pin;
}
void customer::serialize(Archive & ar, const unsigned int version) {
ar & vectorID;
ar & name;
ar & type;
ar & detail;
}
Then when you want to add to file you can just do:
std::ofstream ofs("filename", std::ios::binary); // binary file open
....
// save data to archive
{
boost::archive::text_oarchive oa(ofs);
// write class instance to archive
oa << yourCustomerClass;
}
And the opposite to read the file.
Upvotes: 1