0

I have a simple container class holding a QTextStream. I use it to write to a file. What I want is that the function below adds at the beginning of a stream operator call "LogHandle() << "foo" << 1234;" a prefix. E.g. "LOG:" and at the end a new line endl. Simply adding such a thing on each call of the << operator is not working of course.

Expected output:

Log: foo 1234 *break*

Current code:

class Handle{
public:
    Handle() {
        QString path = QCoreApplication::applicationDirPath();
        path.append("/foo.log");
        _file.setFileName(path);
        _stream.setDevice(&_file);
    }

    QFile _file;
    QTextStream _stream;
};

template <class T>
Handle& operator<< (Handle& out, T msg) {
    out._file.open(QIODevice::WriteOnly | QIODevice::Append);
    out._stream << msg;
    return out;
}
dgrat
  • 2,214
  • 4
  • 24
  • 46
  • If you execute: `Handle h; h << "s1" << "s2" << "s3";` the output must be `"LOG: s1 s2 s3 \n"`. I am right? – eyllanesc Sep 22 '17 at 11:36
  • If so, you know that: `h << "s1" << "s2";` is equivalent to `h << "s1"; h << "s2";` so I ask: At what point is it finished writing in the handler? – eyllanesc Sep 22 '17 at 11:36
  • I think that using QTextStream is not the appropriate option, when the file is written, ie when to add the suffix? – eyllanesc Sep 22 '17 at 11:39
  • Guess, I have to think about this apporach :( – dgrat Sep 22 '17 at 11:40
  • The first thing to be clear is when you add the prefix and the suffix, the prefix is simple, ie in the first script, instead the suffix is something that one must decide because it involves defining the end of the instruction, but that information is impossible to help you – eyllanesc Sep 22 '17 at 11:43

0 Answers0