#include#include QFile file("file.txt"); if (file.open(QIODevice::ReadOnly | QIODevice::Text)) { QTextStream stream(&file); QString line = stream.readLine(); while (!line.isNull()) { // process the line line = stream.readLine(); } file.close(); } else { // error handling }
#include#include QFile file("file.txt"); if (file.open(QIODevice::WriteOnly | QIODevice::Text)) { QTextStream stream(&file); stream << "Hello, world!"; file.close(); } else { // error handling }
#includeThis code demonstrates how to use QTextStream to convert between QString and QByteArray. It first converts a QString to a QByteArray using the toUtf8() function. Then it creates two QTextStream objects, one to read from the byte array and one to write to it. It reads the first line of text from the byte array and writes a new line of text to it. The package library for QTextStream is part of the Qt library.QString str = "Hello, world!"; QByteArray ba = str.toUtf8(); QTextStream in(&ba, QIODevice::ReadOnly); QString line = in.readLine(); QTextStream out(&ba, QIODevice::WriteOnly); out << "New line of text.";