Writing a Class to a File : class save load « File Stream « C++ Tutorial






#include <fstream>
#include <iostream>
using namespace std;
class Animal
{
public:
   Animal(int weight, long days):itsWeight(weight),itsNumberDaysAlive(days){}
   ~Animal(){}

   int GetWeight()const { return itsWeight; }
   void SetWeight(int weight) { itsWeight = weight; }

   long GetDaysAlive()const { return  itsNumberDaysAlive; }
   void SetDaysAlive(long days) { itsNumberDaysAlive = days; }

private:
   int itsWeight;
   long itsNumberDaysAlive;
};

int main(){
   ofstream fout("text.txt",ios::binary);
   if (!fout)
   {
      cout << "Unable to open for writing.\n";
      return(1);
   }

   Animal Bear(50,100);
   fout.write((char*) &Bear,sizeof Bear);

   fout.close();

   ifstream fin("text.txt",ios::binary);
   if (!fin)
   {
      cout << "Unable to open for reading.\n";
      return(1);
   }

   Animal BearTwo(1,1);

   cout << "BearTwo weight: " << BearTwo.GetWeight() << endl;
   cout << "BearTwo days: " << BearTwo.GetDaysAlive() << endl;

   fin.read((char*) &BearTwo, sizeof BearTwo);

   cout << "BearTwo weight: " << BearTwo.GetWeight() << endl;
   cout << "BearTwo days: " << BearTwo.GetDaysAlive() << endl;
   fin.close();
   return 0;
}








12.4.class save load
12.4.1.Save class to a file
12.4.2.Writing a class to a file.
12.4.3.Read class data from file
12.4.4.Writing a Class to a File
12.4.5.Read person object from disk
12.4.6.saves person object to disk
12.4.7.reads and writes several objects to disk