Choose custom line ending for text file writing by Qt

我怕爱的太早我们不能终老 提交于 2019-12-10 19:53:04

问题


When writing a text file in Qt (using QFile and QTextStream), any \n or endl is automatically converted into the right platform specific line ending (e.g. \r\n for Windows).

I would like to let the user choose which file ending is used.

Is there a way to set the desired line ending in Qt without using binary file mode?


回答1:


No, there isn't. The meaning of text mode is "perform line-ending changes to these of the platform". If you want to do anything else, use the binary mode, and implement the conversion by reimplementing e.g. QFile::writeData and 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;
...


来源:https://stackoverflow.com/questions/38777334/choose-custom-line-ending-for-text-file-writing-by-qt

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!