My QTextStream is empty when this code finishes:
QString line1 = "This is line one";
QString line2 = "This is line two";
QString line3 = "This is line three";
QString outputFilename = "temp.txt";
QFile outputFile(outputFilename);
outputFile.open(QIODevice::WriteOnly);
outputFile.open(QIODevice::ReadWrite); // This fixes the problem
QTextStream out1(&outputFile);
out1 << line1 << endl;
out1 << line2 << endl;
out1 << line3 << endl;
outputFile.flush();
QString temp = out1.readAll();
mainclipboard->setText(temp);
outputFile.close();
Here, the QString temp is empty. What have I missed?
Thanks to hyde for the answer.
You open the file backing the QTextStream
as write only, so reading should fail for that reason alone. Just change the open mode.
Also consider the position in the file you are reading from... Use pos()
method to check it, it should tell you that file position is where your write ended. So just seek()
before reading.
Since you are operating on single QTextStream
, flushing shouldn't be necessary. If you had separate objects for reading and writing, then you would need to flush to make sure data is written to the OS (flush the QTextStream
, that also flushes the file, as explained in the docs).