2016-08-04 84 views
3

在Qt中編寫文本文件時(使用QFile和QTextStream),任何\nendl都會自動轉換爲正確的平臺特定行結尾(例如Windows的\r\n)。爲Qt編寫的文本文件選擇自定義行結尾

我想讓用戶選擇使用哪個文件結尾。

有沒有辦法來設置Qt的結束,而無需使用二進制文件模式所需的行?

回答

5

不,沒有。文本模式的含義是「對這些平臺執行換行結束」。如果您想做其他任何事情,請使用二進制模式,然後通過重新實現QFile::writeDataQFile::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; 
...