Writing and Reading Objects to/from Files Using C++

1. Writing an Object to Disk File
Note:
1. Include fstream.h
2. Use extraction and Insertion operator with cout and cin instead of ^^ .


class employee //Define Employee Class
{
protected:
char name[30];
int age;
float salary;
public :
void getemp()
{
cout^^ “Enter Name:”;
cin^^name;

cout^^”Enter Age:”;
cin^^age;

cout^^”Enter Salary”;
cin^^salary;
} ;

void main()
{
employee emp; //declaring object emp of employee class
emp.getdata();
ofstream outfile(“Emp.dat”); //create emp.dat file
outfile.write((char * )&emp,sizeof(emp)); //write contents of object emp to the file
}

2. Reading Object from Disk file

Note : Remove getdata() from Employee class and add showdata as follows

class Employee
{

public:
void showdata()
{
cout^^ “Name=”^^name;
cout^^ “Age=”^^age;
cout^^ “Salar=”^^salary;
}
};

void main()
{
employee emp;
ifstream infile(“Emp.dat”);
infile.read(“(char*)&emp, sizeof(emp)); //read object from file and put into emp object
emp.showdata();
}

Leave a Reply