Write Object into a File

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

Questions by karthik_knight2000   answers by karthik_knight2000

Showing Answers 1 - 13 of 13 Answers

chaamurah

  • Feb 3rd, 2009
 

#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();
}

sim_sam

  • Feb 12th, 2009
 

A function in the class definition can be included which writes to the standard file stream and takes the name of target file as a parameter. Function prototype will be like this:

WriteObjectToFile (const char* fileName)
{
ofstream fout(fileName);
fout<< myVar1<<myVar2<<endl;
fout.close();
}

  Was this answer useful?  Yes

ajrobb

  • Sep 22nd, 2010
 

#include <ostream>

class Fred {
...
public:
  std::ostream & write(std::ostream & out) const;
};

inline std::ostream & operator<<(std::ostream out, Fred const & fred) {
  return fred.write(out);
}

int main() {
  Fred fred;
...
  std::cout << fred << 'n';
}

  Was this answer useful?  Yes

hi

  • Nov 9th, 2016
 

I think the final fobj.display_detail(); in your code needs to change to eobj.display_detail();

  Was this answer useful?  Yes

Arman

  • Jan 25th, 2018
 

You can write the object into file after serializing it. It is important to note that there are two types of objects: "persistence" and "non persistence". persistence objects are those which can be serialized and saved in file system.

  Was this answer useful?  Yes

Give your answer:

If you think the above answer is not correct, Please select a reason and add your answer below.

 

Related Answered Questions

 

Related Open Questions