Search code examples
c++qtline-endingseol

Choose custom line ending for text file writing by Qt


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?


Solution

  • 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;
    ...