选择Qt文本文件写入的自定义行结尾

Sil*_*cer 3 c++ qt line-endings eol

在Qt中编写文本文件(使用QFile和QTextStream)时,任何\n或endl自动转换为正确的平台特定行结束(例如,\r\n对于Windows).

我想让用户选择使用哪个文件结尾.

有没有办法在不使用二进制文件模式的情况下设置以Qt结尾的所需行?

Rei*_*ica 5

不,没有.文本模式的含义是"对这些平台执行行结束更改".如果你想做任何其他事情,请使用二进制模式,并通过重新实现例如QFile::writeData和实现转换QFile::readData.

template <class Base> class TextFile : public Base {
  QByteArray m_ending;
  qint64 writeData(const char * data, qint64 maxSize) override {
    Q_ASSERT(maxSize <= std::numeric_limits<int>::max());
    QByteArray buf{data, maxSize};
    buf.replace("\n", m_ending.constData());
    auto len = Base::writeData(buf.constData(), buf.size());
    if (len != buf.size()) {
      // QFile/QSaveFile won't ever return a partial size, since the user
      // such as `QDataStream` can't cope with it.
      if (len != -1) qWarning() << "partial writeData() is not supported for files";
      return -1; 
    }
    return len;
  }
  ...
}

TextFile<QFile> myFile;
...
Run Code Online (Sandbox Code Playgroud)