Writing and Reading Objects into Files:
The objects of a class can also be written into the file on the disk and read back from the file. The objects are written & read in binary format with the “write” member function. Similarly, they are read from the tile with the “read” member function.
When an object is written on the disk into a tile then only contents of the data members are stored as blocks of bytes. Similarly, the blocks of bytes are read back from disk into the computer memory.
The syntax of the “write” function & the “read” function fur writing & reading an object of a class or data of “struct” type are same. The syntax of the “write” function to write an object is:
The syntax of “read” function to read object is:
Where
object: represents the object created for writing data into the file.
obj: represents object of user defined class.
Example:
Write a program to store records of employees on the disk in the form of objects.
#include <iostream.h>
#include <fstream.h>
#include <conio.h>
#include <stdlib.h>
class abc
{
private:
char code [5], name[15], address[20];
int pay;
public:
void input (void);
{
cout << “Enter code ?”;
cin >> code;
cout << “Enter Name ?”;
cin >> name;
cout << “Enter Address ?”;
cin >> address;
cout<< “Enter Pay ?”;
cin >> pay;
}
};
main ( )
{
abc rec;
char op;
ofstream addrec (“employee.dat”,ios : : binary);
if (!addrec)
{
cerr << “File opening error” <<endl;
exit (1) ;
}
do
{
clrscr ( );
rec.input ( );
addrec.write ((char*)&rec,sizeof (rec));
cout << “More Records [y/n] ? “; cin >> op;
}while(op== ‘y’ || op == ‘y’);
addrec.close ( );
}
comment closed