开发者

writing an object to a file in cpp

I am trying to write the conte开发者_开发百科nts of an object into a file. This is my code

void Write_data_intoFile(Customer c1)
{
ofstream fout("cust_details.txt", ios::out | ios::app); 
fout.write(reinterpret_cast<char*> (&c1),sizeof c1);
fout.close();
}

This is how i call the function

c[ Customer_count ].Write_data_intoFile(c[ Customer_count ]);

The program works fine, but the contents are not written in the file. It shows a red colour mark saying it cannot open the file. How to solve this

class Customer
{
char name[25];
int id;
}

I created the objects, globally, by

Customer c[20];

I am trying to write it in a text format


OK, first you need to write a function for text I/O of Customer. Traditionally that function is called operator<<. So you need something like this

ostream& operator<<(ostream& out, const Customer& c)
{
  return out << c.name << ' ' << c.id << '\n';
}

Maybe (it's hard to be sure) you need to declare this function as a friend of your Customer class, if you get errors about access or private then you probably need to add this line

friend ostream& operator<<(ostream& out, const Customer& c);

inside your Customer class.

Then you need to call this function from inside your other function, like this

void Write_data_intoFile(Customer c1)
{
  ofstream fout("cust_details.txt", ios::out | ios::app); 
  fout << c1;
  fout.close();
}

Then you really need to read a good book on C++, it's hard to get this stuff right otherwise. Any problems post again.


Instead of reinventing the wheel in a potentially dangerous way Boost.Serialization can solve this for you, hiding the dirty details.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜