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?
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
.