//Listing 14.09 Writing a Class to a File
#include <fstream>
#include <iostream>
using namespace std;
class Animal {
public:
Animal(int weight, long days): itsWeight(weight), DaysAlive(days){}
~Animal(){}
int GetWeight()const { return itsWeight; }
void SetWeight(int weight) { itsWeight = weight; }
long GetDaysAlive()const { return DaysAlive; }
void SetDaysAlive(long days) { DaysAlive = days; }
private:
int itsWeight;
long DaysAlive;
};
int main() // returns 1 on error
{
char fileName[80] = "";
cout << "Please enter the file name: ";
cin >> fileName;
ofstream fout(fileName, ios::binary);
if (!fout)
{
cout << "Unable to open " << fileName << " for writing.\n";
return(1);
}
Animal bear1(50,100);
fout.write(reinterpret_cast<char*>(&bear1), sizeof bear1);
fout.close();
ifstream fin(fileName, ios::binary);
if (!fin)
{
cout << "Unable to open " << fileName << " for reading.\n";
return(1);
}
Animal bear2(1,1);
cout << "BearTwo weight: " << bear2.GetWeight() << endl;
cout << "BearTwo days: " << bear2.GetDaysAlive() << endl;
fin.read(reinterpret_cast<char*>(&bear2), sizeof bear2);
cout << "BearTwo weight: " << bear2.GetWeight() << endl;
cout << "BearTwo days: " << bear2.GetDaysAlive() << endl;
fin.close();
return 0;
}