#include <QCoreApplication> #include <QTextStream7gt; #include <QFile> #include <QDebug7gt; void write() { QFile file("C:/Test/simple.txt"); if(file.open(QIODevice::WriteOnly | QIODevice::Text)) { // We're going to streaming text to the file QTextStream stream(&file); stream << "Debussy\n"; stream << "Rabel\n"; file.close(); qDebug() << "Writing finished"; } } void read() { QFile file("C:/Test/simple.txt"); if(file.open(QIODevice::ReadOnly|QIODevice::Text)) { // We're going to streaming the file // to the QString QTextStream stream(&file); QString line; do { line = stream.readLine(); qDebug() << line; } while(!line.isNull()); file.close(); qDebug() << "Reading finished"; } } int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); write(); read(); return a.exec(); }
Output:
Writing finished "Debussy" "Rabel" "" Reading finished
It's also common to use QTextStream to read console input and write console output. QTextStream is locale aware, and will automatically decode standard input using the correct codec. Example:
QTextStream stream(stdin);
QString line;
do {
line = stream.readLine();
} while (!line.isNull());