Saturday, April 7, 2012

Break down of Fstream example in class

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

class Employee{
  char _name[15];
  char _lastname[30];
  int _empno;
  double _salary;
public:
  Employee(const char* name="", const char* lastname="", int empno=0, double salary=0.0){
     set(name, lastname, empno, salary);
  }
  void set(const char* name="", const char* lastname="", int empno=0, double salary=0.0){
    strcpy(_name, name);
    strcpy(_lastname, lastname);
    _empno = empno;
    _salary = salary;
  }
  ostream& print(ostream& OS)const{
    return OS<<"Name: "<<_name<<" "<<_lastname<<endl<<"EmpNo: "<<_empno
      <<", Salary: "<<_salary;
  }
  virtual ~Employee(){
    //print(cout)<<"is dead!!!!"<<endl;
  }
};
ostream& operator<<(ostream& OS, const Employee& E){
  return E.print(OS);
}

int main(){
  Employee E;
  ifstream file;
  file.open("emp.bin",ios::binary);//open the file emp.bin, consider the stream as Binary instead of text
  file.seekg((ios::off_type)0, ios::end);//set the cursor position from (0), to the end of the file(ios::end)
  int loc = file.tellg();//set loc to the cursor position (tellg())
  cout << sizeof(Employee) << endl;
  while(loc > 0 ){//while loc is greater than zero go in here.
    loc -= sizeof(Employee);//subtract loc by the size of an Employee object (72)
    file.seekg((ios::pos_type)loc);//put the cursor position to loc (first time in is 288 then, 216, 144, 72, 0)
    file.read((char*)&E, sizeof(Employee));//read (sizeof(Employees) = 72) of character from the current position and store it in &E, which is cast to a char*
    cout<<E<<endl;
  }
  return 0;
}

No comments:

Post a Comment