QFile中使用QIODevice::Text打开文件时导致的读取文件总大小出现偏差的问题解决办法

介绍

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’换行符,则大小读取正常。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值