0

I tried to save some info to the text file using QTextStream. The code is given below:

QFile fi(QString("result.txt"));
fi.remove();
if(!fi.open(QIODevice::Append)) {
    qDebug()<<"Cannot open file!";
    return -1;
}

QTextStream ts(&fi);
float num = 1, error = 2;
ts<<"num="<<num<<"\t"<<"error="<<error<<endl;

However, the code does not work. The file is created, but nothing is written, i.e., the file is empty.

After some research, I found that I should change the open mode to QIODevice::Text | QIODevice::Append to make the code work. Otherwise the "\t" character must be removed. Does it mean that the QIODevice::Text is designed specifically for the special characters such as "\t" to work in writing to files?

user957121
  • 2,946
  • 4
  • 24
  • 36

1 Answers1

1

I can't reproduce. The following works perfectly on Windows, OS X and Linux, with Qt 5.9. Please fix your example to be complete and reproducible. E.g. take the code below, and make it fail.

// https://github.com/KubaO/stackoverflown/tree/master/questions/stream-49779857
#include <QtCore>

QByteArray readAll(const QString &fileName) {
   QFile f(fileName);
   if (f.open(QIODevice::ReadOnly))
      return f.readAll();
   return {};
}

int main() {
   auto tmp = QStandardPaths::writableLocation(QStandardPaths::TempLocation);
   auto fileName = QStringLiteral("%1/com.stackoverflow.questions.49779857-result.txt")
         .arg(tmp);
   QFile file(fileName);
   file.remove();
   if (!file.open(QIODevice::Append))
      qFatal("Cannot open file!");

   QTextStream ts(&file);
   auto num = 1.0f, error = 2.0f;
   ts << "num=" << num << "\t" << "error=" << error << endl;
   file.close();

   Q_ASSERT(file.exists());
   Q_ASSERT(readAll(fileName) == "num=1\terror=2\n");
}
Kuba hasn't forgotten Monica
  • 95,931
  • 16
  • 151
  • 313