Q. Write a programme in C++ to write and later retrieve objects to form file.
Ans.
# include
# include < c type. h > // for trouper
# include < string. h > // for strlen
# define MAX NAME 40
Class person
{
Private :
Char name [MAX NAME];
Int age;
Public :
// this functions writes the class's data members to the file void write (of stream & of s)
{
Of. S write (name, strlen (name));
Of a << ends;
Of s write ((char *) & age, size of (age));
}
// this functions reads the class's data members from the file.
// it returns non zero if no errors were encountered while reading
Int read (if stream & is)
{ is. Get (name, MAX NAME,0);
Name [ is. G count () ] = 0;
Is. Ignore (1); // ignore the NULL terminator in the file.
Is. Read (( char * ) & age, size of (age));
Return is. good ();
}
// stream operator, << overloading
Friend function & operator << (of stream & os, person & b);
// stream operator, << operator overloading
Friend function & operator << (is stream & os, person & b);
// output file stream operator << (of stream & fos, person & b)
{
b. write (fos); return fos;
}
// output file stream operator overloading
Friend function of stream & operator << (of stream & fos, person & b)
{
b. write (fos); return fos;
}
// output file stream operator overloading
Friend function of stream & operator << (if stream & fos, person & b)
b. read (fos); return fos
}
};
I stream & operator >> (i stream & fos, person & b)
{
Cout << "Name:",
Is << ws; // flush input buffer
Is. Get (b. Name, MAX NAME);
Cout << "Age :" ;
Is >> ws >> b. Age;
Return is;
}
Of stream & operator << (o stream & os, person & b)
{
Os << b. Name << end l;
Os << b. age << end l;
Return os;
}
Void main ()
{