GeekInterview.com
   Home |  Tech FAQ  |   Interview Questions |  Placement Papers |  Tech Articles |  Learn |  Freelance Projects |  Online Testing |  Geeks Talk |  Job Postings |  Knowledge Base | Site Search |  Add/Ask Question

  GeekInterview.com  >  Interview Questions  >  Programming  >  C++

 Print  |  
Question:  Write Object into a File

Answer: How will you write object into file using file concepts in C++?


February 02, 2009 00:08:34 #1
 chaamurah   Member Since: February 2009    Total Comments: 1 

RE: Write Object into a File
 
#include
#include           //for i/o operations with respect to files


class Employee
{
int id;
        char name[20];
public:
void set_details()
{
cout<<"enter name"<
cin>>name; //dont give blanks in between the name
cout<<"enter id"<
cin>>id;
}
void display_details()
{
cout<<"name : "<
cout<<"id :"<
}
};

int main()
{
//open the file file_name for writing objects.fstream object used for both input and output operations with respect to files
fstream fobj("file_name.txt",ios::out|ios::app);

Employee eobj;
char ch;
//to write in to file

//this do while loop will take the details of employee to an object and writes in to the file until u press 'n' or than 'y'

do
{
cout<<"enter the employee details"<
eobj.set_details();
//using write method we can write in to the file 
fobj.write ( (char *)(&eobj) , sizeof(eobj) );
cout<<"do u want to  enter one more record (Y OR N)"<
cin>>ch;
}while(ch=='y' || ch =='Y')

fobj.close();

//to read from the file

fobj.open("file_name.txt",ios::read);

//read all the objects using read method and displaying.when read encounters end of file returns null.

while(  fobj.read (  (char *)&eobj , sizeof(eobj) )  )
fobj.display_details();
fobj.close();
}
     

 

Back To Question