Insertion Operator

I need to to create a stream output as like cout;
fout<<"number:"<<6<<endl;
will write everything to a file which i have specified or default.

I had came across friend ostream& operator << (ofstream& fout,ClassA &obj) etc. But I need to do as like 'QTextStream' in Qt how can i do that?
[QTextStream &operator<<(const QString &s);]
FileStream &operator<<(const string &s);

FileStream fout("log.txt");
fout<<"number:"<<6<<endl;

Any suggestions?
Last edited on
You could make the operator a member of FileStream

1
2
3
4
5
6
7
#include <string>

FileStream& FileStream::operator<<(const std::string &s)
{
   //do insertion operation
   return *this;
}


You could also make the operator<< a template function.
Last edited on
thanks shacktar!

FilesWriter& operator << (const long int ovalue)
{
ofstream file;
file.open(filename.c_str(), ios::out | ios::app | ios::binary);
file << ovalue;
file.close();
return *this;
}
It would make a lot more sense for the file to remain open, rather than you closing and reopening it for every write. Closing and reopening is very slow.

Also, what's the point of this FilesWriter class? Why not juse use ofstream directly?
Topic archived. No new replies allowed.