Search code examples
c++qtfilestream

What are the advantages of streams in C++?


I'm mostly using Qt framework in C++. Can anyone explain me the advantages of using textstream objects instead of using directly objects?

Here is an example code without a QTextStream;

QFile file("asd.txt");
// assuming that file exists
file.open(QIODevice::Append);
file.write("asd");
file.close();

What are the advantages (or disadvantages) of using below code instead the above one;

QFile file("asd.txt");
// assuming that file exists
file.open(QIODevice::Append);
QTextStream tStream(file);
file << "asd";
file.close();

Thanks in advance.


Solution

  • QFile::write either writes a nul terminated C string, or binary data that you give it.

    QTextStream on the other hand does text formatting/conversion.

    • It deals with text output/input only, not arbitrary binary data.
    • You can give it a primitive type (int, float, long etc.) and it'll convert it to a textual representation
    • You can have it read text and convert to primitive types.
    • You can have it do formatted output, e.g. pad or left/right adjust text.
    • You can set the text encoding (e.g. UTF-8, UTF-16)
    • It buffers the data, potentially resulting in fewer system calls being made. Note that this means your code should call tStream.flush(); before you close the file.