How to write an object to a file in c++ ?

In C++, for writing and accessing an object to/from a file we may use write and read functions provided by fstream.

Consider this example :




#include <iostream.h>
#include <conio.h>
#include <fstream.h>

class Student
{
int roll;
char name[30];

public :

void getDetails()
{
cout<<"Enter Student Details"<<endl;
cout<<"Roll No. : ";
cin>>roll;
cout<<"Name : ";
cin>>name;
}

void showDetails()
{
cout<<endl<<"Student Details"<<endl;
cout<<"Roll No. : "<<roll<<endl;
cout<<"Name : "<<name<<endl;
}

};

int main()
{
Student s1;
Student s2;


s1.getDetails(); // taking details from user


/* Writing s1 object to Student.txt file */

ofstream fout("c:\\Student.txt"); // open file for writing
fout.write((char*)&s1,sizeof(s1)); // write s1 object to file
fout.close(); // close the file

cout<<"\nData is saved in file, press any key to retrieve it\n\n";
getch();


/* Reading saved object from Student.txt file and store it in s2 object */

ifstream fin("c:\\Student.txt"); //open file for reading
fin.read((char*)&s2,sizeof(s2)); // save accessed data in s2 object
fin.close(); // close the file

cout<<"\nData read from file : \n";

s2.showDetails(); // display data

return 0;
}

Output :