6

Is there any differences in two ways of writing text in QFile?

By using write method:

QFile file("test.txt");
if(file.open(QIODevice::WriteOnly | QIODevice::Text)) {
    file.write("My Text\n");
}
file.close();

Or by using QTextStream:

QFile file("test.txt")
if(file.open(QIODevice::WriteOnly | QIODevice::Text)) {
     QTextStream out(&file);
     out << "My Text\n";
}
file.close()

Which way is preferred? Is there any differences in performance?

Alexshev92
  • 171
  • 4
  • 8
  • 2
    it's a matter of usage. In your example there is not much difference. The hardcoded string in the first example will get converted to QByteArray and then written. In the second example it will not get converted (well maybe deeper under the hood). In case you are not going to use hardcoded string (most probably ;-) ) you may find it easier to use the latter, or even `QDataStream` – Amfasis Oct 29 '18 at 08:29
  • Which part of the [documentation](http://doc.qt.io/qt-5/qtextstream.html#details) did confuse you? – scopchanov Oct 29 '18 at 13:57
  • 1
    I've read it, but I don't understand differences `QTextStream` and `write`. – Alexshev92 Oct 29 '18 at 14:12

1 Answers1

4

QIODevice::write is the low-level byte-oriented interface for writing raw data to a device. QTextStream is a higher-level interface for writing formatted text. QTextStream is probably implemented in terms of QIODevice::write under the hood.

One of the principal use cases for QTextStream is for writing QString data. The text stream handles the conversion from UTF-16 to your locale's default (usually 8-bit) encoding (or any other encoding via QTextStream::setCodec).

QTextStream almost certainly performs worse since it does more. However, in most use cases the difference will be negligible. If you're building a big string of raw data manually, then you should probably use QIODevice::write. If you want to write formatted text (that may include QString), you should probably chose QTextStream.

Jason Haslam
  • 2,617
  • 13
  • 19