Fstream and stream operator << difference

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

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

Thanks jack

+3
source share
4 answers

You must overload the statement for ostream, then you can use it naturally for an instance of any class that comes from this: fromstream, fstream (inherits from iostream, which inherits both istream and ostream), ostringstream and stringstream (inherits iostream too)

std::ostream& operator<<(std::ostream& os, const MyData&);
+15
source

std::ostream. , ? std::cout, .

iostreams . .

+1

AFAIK, ofstream("file.txt") fstream("file.txt", ios::out).

0

, fstream. append-only, ofstream. , , ios::app.

0

Source: https://habr.com/ru/post/1752973/


All Articles