Object Serialization

Save object to file with customized operator

#include <iostream>
#include <fstream>
#include <cstring>
using namespace std;
   
class phonebook {
  char name[80];
  char areacode[4];
  char prefix[4];
  char num[5];
public:
  phonebook() { };
  phonebook(char *n, char *a, char *p, char *nm)
  {
    strcpy(name, n);
    strcpy(areacode, a);
    strcpy(prefix, p);
    strcpy(num, nm);
  }
  friend ostream &operator<<(ostream &stream, phonebook o);
  friend istream &operator>>(istream &stream, phonebook &o);
};
   
ostream &operator<<(ostream &stream, phonebook o)
{
  stream << o.name << " ";
  stream << "(" << o.areacode << ") ";
  stream << o.prefix << "-";
  stream << o.num << "\n";
  return stream; // must return stream
}
   
istream &operator>>(istream &stream, phonebook &o)
{
  cout << "Enter name: ";
  stream >> o.name;
  cout << "Enter area code: ";
  stream >> o.areacode;
  cout << "Enter prefix: ";
  stream >> o.prefix;
  cout << "Enter number: ";
  stream >> o.num;
  cout << "\n";
  return stream;
}
   
int main()
{
  phonebook a;
  char c;
   
  fstream pb("phone", ios::in | ios::out | ios::app);
   
  if(!pb) {
    cout << "Cannot open phone book file.\n";
    return 1;
  }
   
  cin >> a;
  cout << "Entry is: ";
  cout << a;  // show on screen
  pb << a;  // write to disk

  char ch;
  pb.seekg(0, ios::beg);
  while(!pb.eof()) {
     pb.get(ch);
     if(!pb.eof()) cout << ch;
  }
  pb.clear();  // reset eof
  cout << endl;
  
  pb.close();
  
}
Using Command-Line Arguments to Get a Filenam

#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(int argc, char *argv[])
{
   if (argc != 2)
   {
      cout << "Usage: " << argv[0] << " <filename>" << endl;
      return(1);
   }

   ofstream fout(argv[1],ios::binary);
   if (!fout)
   {
      cout << "Unable to open " << argv[1] << " for writing.\n";
      return(1);
   }

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

   fout.close();

   ifstream fin(argv[1],ios::binary);
   if (!fin)
   {
      cout << "Unable to open " << argv[1] << " 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;
}
  

Save and read class back and forth to a file

#include <iostream>
#include <fstream>
#include <cstring>
using namespace std;

class Person {
  char name[80];
  char areaCode[4];
  char prefix[4];
  char num[5];
public:
  Person() { };
  Person(char *n, char *a, char *p, char *nm)
  {
    strcpy(name, n);
    strcpy(areaCode, a);
    strcpy(prefix, p);
    strcpy(num, nm);
  }
  friend ostream &operator<<(ostream &stream, Person o);
  friend istream &operator>>(istream &stream, Person &o);
};

ostream &operator<<(ostream &stream, Person o)
{
  stream << o.name << " ";
  stream << "(" << o.areaCode << ") ";
  stream << o.prefix << "-";
  stream << o.num << endl;
  return stream; // must return stream
}

istream &operator>>(istream &stream, Person &o)
{
  cout << "Enter name: ";
  stream >> o.name;
  cout << "Enter area code: ";
  stream >> o.areaCode;
  cout << "Enter prefix: ";
  stream >> o.prefix;
  cout << "Enter number: ";
  stream >> o.num;
  cout << endl;
  return stream;
}

int main()
{
  Person personObject;
  char c;

  fstream pb("phone", ios::in | ios::out | ios::app);

  if(!pb) {
    cout << "Cannot open phone book file.\n";
    return 1;
  }

  for(;;) {
    do {
      cout << "1. Enter numbers\n";
      cout << "2. Display numbers\n";
      cout << "3. Quit\n";
      cout << "\nEnter a choice: ";
      cin >> c;
    } while(c < '1' || c > '3');

    switch(c) {
      case '1':
        cin >> personObject;
        cout << "Entry is: ";
        cout << personObject;                       
        pb << personObject;                         
        break;
      case '2':
        char ch;
        pb.seekg(0, ios::beg);
        while(!pb.eof()) {
          pb.get(ch);
          if(!pb.eof()) 
             cout << ch;
        }
        pb.clear();                      
        cout << endl;
        break;
      case '3':
        pb.close();
        return 0;
    }
  }
}

Serialize object Demo

#include <iostream>
#include <fstream>
#include <cstring>
using namespace std;

#define SIZE 40

class Product {
  char item[SIZE]; 
  int onhand;      
  double cost;     
public:
  Product(char *i, int o, double c)
  {
    strcpy(item, i);
    onhand = o;
    cost = c;
  }
  void store(fstream &stream);
  void retrieve(fstream &stream);
  friend ostream &operator<<(ostream &stream, Product ob);
  friend istream &operator>>(istream &stream, Product &ob);
};

ostream &operator<<(ostream &stream, Product ob)
{
  stream << ob.item << ": " << ob.onhand;
  stream << " on hand at $" << ob.cost << '\n';

  return stream;
}

istream &operator>>(istream &stream, Product &ob)
{
  cout << "Enter item name: ";
  stream >> ob.item;
  cout << "Enter number on hand: ";
  stream >> ob.onhand;
  cout << "Enter cost: ";
  stream >> ob.cost;

  return stream;
}

void Product::store(fstream &stream)
{
  stream.write(item, SIZE);
  stream.write((char *) &onhand, sizeof(int));
  stream.write((char *) &cost, sizeof(double));
}

void Product::retrieve(fstream &stream)
{
  stream.read(item, SIZE);
  stream.read((char *) &onhand, sizeof(int));
  stream.read((char *) &cost, sizeof(double));
}

int main()
{
  fstream fileStream("fileStream", ios::out | ios::binary); 
  int i;

  Product productObject1("p", 12, 4.95);
  Product productObject2("h", 5, 9.45);
  Product productObject3("w", 22, 13.90);
  Product productObject4("", 0, 0.0);

  if(!fileStream) {
    cout << "Cannot open file for output.\n";
    return 1;
  }
  // write to file
  productObject1.store(fileStream);
  productObject2.store(fileStream);
  productObject3.store(fileStream);

  fileStream.close();

  // open for input
  fileStream.open("fileStream", ios::in | ios::binary); 

  if(!fileStream) {
    cout << "Cannot open file for input.\n";
    return 1;
  }

  do {
    cout << "Record # (-1 to quit): ";
    cin >> i;
    if(i == -1) 
       break;
    fileStream.seekg(i*(SIZE+sizeof(int)+sizeof(double)), ios::beg);
    productObject4.retrieve(fileStream);
    cout << productObject4;
  } while(fileStream.good());

  fileStream.close();

  return 0;
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值