为 Qt 写入的文本文件选择自定义行结尾
Choose custom line ending for text file writing by Qt
在 Qt 中写入文本文件时(使用 QFile 和 QTextStream),任何 \n
或 endl
都会自动转换为正确的平台特定行结尾(例如 \r\n
for Windows).
我想让用户选择使用哪个文件结尾。
有没有办法在不使用二进制文件模式的情况下设置以 Qt 结尾的所需行?
不,没有。文本模式的含义是"perform line-ending changes to these of the platform"。如果您想做任何其他事情,请使用二进制模式,并通过重新实现例如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;
...
在 Qt 中写入文本文件时(使用 QFile 和 QTextStream),任何 \n
或 endl
都会自动转换为正确的平台特定行结尾(例如 \r\n
for Windows).
我想让用户选择使用哪个文件结尾。
有没有办法在不使用二进制文件模式的情况下设置以 Qt 结尾的所需行?
不,没有。文本模式的含义是"perform line-ending changes to these of the platform"。如果您想做任何其他事情,请使用二进制模式,并通过重新实现例如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;
...