Search code examples
c++qtstdoutqdatastreamqtextstream

How to write binary data to stdout in Qt5


QTextStream allows me to wrap stdout so that I can write using Qt spesifics to stdout with conveneince. Example:

QTextStream qout(stdout);
qout << QString("Some qt spesific stuff: %1\n").arg(1337);

However while QTextStream is really useful, it does not support binary data. All data that passes through it is expected to follow valid character sets and encodings (unicode/UTF-8 etc).

So the logical replacement if I want to output raw binary data to stdout would be to replace QTextStream with QDataStream. However that class does not allow me to wrap stdout (it has no constructors that takes std file handle).

So what options do I have for having "Qt convenience" while writing binary data to stdout? And what would be next best thing?

PS: I know writing binary data to std out is not always good idea. However, I really need to do it.


Solution

  • You can open stdout with this overload of QFile::open like this:

    QFile my_stdout;
    if (my_stdout.open(1, QIODevice::WriteOnly)) {
        QDataStream qout(my_stdout);
        qout << QString("Some qt spesific stuff: %1\n").arg(42);
    }