tags:

views:

94

answers:

4

I want to overload operator << to serialize an object to a file (append). Which stream should I use? ofstream or fstream? what is the difference?

std::ofstream& operator<<(std::ofstream& ofs, const MyData&); std::fstream& operator<<(std::fstream& fs, const MyData&)

Thanks Jack

A: 

AFAIK, ofstream("file.txt") is the same as fstream("file.txt", ios::out).

Gabi Purcaru
A: 

If you also want to read from the same file, use fstream. If append-only, use ofstream. In either case, if you don't want to overwrite existing data, use the ios::app flag when opening.

Ben Voigt
+7  A: 

You should overload the operator for ostream, then you can use it naturally for an instance of any class which derives from that - ofstream, fstream (inherits from iostream, which inherits from both istream and ostream), ostringstream and stringstream (inherits iostream, too)

std::ostream& operator<<(std::ostream& os, const MyData&);
matja
+1 from me. I came within an ace of posting a very similar question this morning.
Brian Hooper
+1  A: 

It would make more sense to overload for std::ostream. Why should your implementation be restricted to a special type of output stream if it can be more general? You also get the benfit of printing your serialization to std::cout which simplyfies debugging.

A good overview about the relations of iostreams and the usage of inheritance is given here. Also every overview page to a specific streams shows the inheritance relations.

pmr