【问题标题】:QFile ignoring last newlineQFile忽略最后一个换行符
【发布时间】:2016-07-13 09:48:50
【问题描述】:

我正在使用 Qt 读取文件

  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();

这种方法的问题是:我无法在文件末尾读取额外的换行符。

假设我有以下文本文件

Hello world\r\n
\r\n

我无法为最后一行 \r\n 获取空字符串。我该如何解决这个问题?

【问题讨论】:

    标签: c++ qt qfile qtextstream


    【解决方案1】:

    根据http://doc.qt.io/qt-4.8/qtextstream.html#readLine \r\n 总是被修剪。所以你会在每一个阅读行中错过它们。你可以:

    a) 使用 readLine() 后将行终止符添加到读取字符串中

    b) 使用QFiles.readLine() 读入不接触读取字节的QByteArray

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

    c) 使用另一种方法来读取文件,例如std::istream。请参阅http://www.cplusplus.com/reference/istream/istream/getline/ 以获取等效的getline

    【讨论】:

      【解决方案2】:

      我认为换行符将被删除。请参阅 QTextStream 的 Qt 文档。

      您必须使用 readAll() 或者如果换行符为空,请自行添加 '\n\r'。

      【讨论】:

        猜你喜欢
        • 2015-07-30
        • 1970-01-01
        • 2020-02-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-09-25
        • 2021-06-17
        相关资源
        最近更新 更多