在Qt中(使用QFile和QTextStream)编写文本文件时,任何\n
或endl
自动转换为正确的平台特定行结尾(例如,\r\n
对于Windows)。
我想让用户选择使用哪个文件结尾。
有没有一种方法可以设置所需的以Qt结尾的行而无需使用二进制文件模式?
不,没有。文本模式的含义是“对平台的行尾进行更改”。如果您想做其他事情,请使用二进制模式,并通过重新实现egQFile::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;
...
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句