介绍
Qt中提供了QFile进行文件操作,QFile中有open()函数。
[virtual] bool QFile::open(OpenMode mode),其中,mode指的是打开的方式,有QIODevice::ReadOnly,QIODevice::WriteOnly,QIODevice::ReadWrite,QIODevice::Text等打开方式。
问题描述
在打开文件时即open函数中是否加入QIODevice::Text这个标志会导致读取文件总大小偏小。
代码示例
#include "widget.h"
#include "ui_widget.h"
Widget::Widget(QWidget *parent) :
QWidget(parent),
ui(new Ui::Widget)
{
ui->setupUi(this);
#if 0
QFile testFile("/home/zefin/Desktop/TestFile.NC");
qDebug() << "testFile's size:" << testFile.size();
if (!testFile.open(QIODevice::ReadOnly | QIODevice::Text)) {
qDebug() << "Open file failed.";
return;
}
qDebug() << "Open(QIODevice::ReadOnly | QIODevice::Text) file succeed.";
int readLength = 0;
QByteArray textBuffer;
while (true) {
textBuffer = testFile.readLine();
readLength += textBuffer.size();
if (textBuffer.isEmpty()) {
break;
}
}
qDebug() << "readLength:" << readLength;
#else
QFile testFile("/home/zefin/Desktop/TestFile.NC");
qDebug() << "testFile's size:" << testFile.size();
if (!testFile.open(QIODevice::ReadOnly)) {
qDebug() << "Open file failed.";
return;
}
qDebug() << "Open(QIODevice::ReadOnly) file succeed.";
int readLength = 0;
QByteArray textBuffer;
while (true) {
textBuffer = testFile.readLine();
readLength += textBuffer.size();
if (textBuffer.isEmpty()) {
break;
}
}
qDebug() << "readLength:" << readLength;
#endif
}
Widget::~Widget()
{
delete ui;
}
两种情况打印的结果分别是:
1:
testFile’s size: 38509
Open(QIODevice::ReadOnly | QIODevice::Text) file succeed.
readLength: 37704
2:
testFile’s size: 38509
Open(QIODevice::ReadOnly) file succeed.
readLength: 38509
导致此问题的原因:
QIODevice::Text这个标志在Qt助手中的解释为:When reading, the end-of-line terminators are translated to ‘\n’. When writing, the end-of-line terminators are translated to the local encoding, for example ‘\r\n’ for Win32.
当读取文件时,行末的结束符会转化为’\n’。当写入文件时,会将行末结束符转为当前的编码符号,如在Win32平台下的’\r\n’。
因此,如果一个文件中含有’\r’的换行符的话,利用QIODevice::Text打开读取时会被转化为’\n’,导致最终读取出的大小偏小。所测试的文件正是因此造成的。如果全是’\n’换行符,则大小读取正常。