1

I'm using Qt to read a file

  std::vector<QString> text;

  QFile f(file);
  if (f.open(QFile::ReadWrite | QFile::Text) == false)
    throw my_exception();

  QTextStream in(&f);
  QString line;
  while(!in.atEnd()) {
    line = in.readLine();

    text.push_back(line);
  }
  f.close();

the problem with this approach is: I can't read extra newlines at the end of the file.

Suppose I have the following text file

Hello world\r\n
\r\n

I'm unable to get an empty string for the last \r\n line. How can I solve this?

Dean
  • 6,610
  • 6
  • 40
  • 90

2 Answers2

0

I think the newlines will be stripped. See Qt documentation of QTextStream.

You have to use readAll() or if newline is empty add '\n\r' by yourself.

Kombinator
  • 107
  • 6
0

According to http://doc.qt.io/qt-4.8/qtextstream.html#readLine \r\n are always getting trimmed. So you will miss them in every read line. You could:

a) Add line terminators to the read strings after having used readLine()

b) Use QFiles.readLine() to read into a QByteArray which doesn't touch the read bytes:

while (!f.atEnd()) {
    QByteArray line = f.readLine();
    process_line(line);
}

c) Use another approach for reading the file, e.g. std::istream. See http://www.cplusplus.com/reference/istream/istream/getline/ for the equivalent getline.

Wum
  • 306
  • 1
  • 10