Writing text in QFile

Viewed 6216

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?

1 Answers

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.

Related