【问题标题】:Why is the QByteArray read from a file smaller than the newly downloaded QByteArray?为什么从文件中读取的 QByteArray 比新下载的 QByteArray 小?
【发布时间】:2015-09-28 02:51:29
【问题描述】:

我正在尝试将已保存的 html 文件的 QByteArray 与刚刚下载的 QByteArray 进行比较。我必须将文件内容的QString 转换为QByteArray 以便比较它们(反之亦然),并且比较字节似乎是最干净的方法,但是当从QString 转换为QByteArray 时,大小为新的 QByteArray 比它应该的要小。 QByteArray QString::toLocal8Bit() const 声明如果未定义,字符将被抑制或替换。它还说它默认使用toLatin1(),并尝试使用ASCII,因为这是网站编码的内容。我仍然得到相同的结果。

bool NewsBulletin::compareDownload(QByteArray new_contents, QString filename)
{
    bool return_what = false;
    qDebug() << "I am in compareDownload";
//    qDebug() << new_contents[1];
//    qDebug() << new_contents[1] << endl
//             << new_contents[2];
    QFile file(application_path + filename);
    if (file.exists())
    {
//        QString new_contents_qstr(new_contents);
        file.open(QIODevice::ReadOnly | QIODevice::Text);
        QTextStream in(&file);
        QTextCodec::setCodecForLocale(QTextCodec::codecForName("ASCII"));
        QString file_contents = in.readAll();
        QByteArray file_byte_array = file_contents.toLocal8Bit();
        qDebug() << "outputting new file array";
        qDebug() << new_contents[5] << new_contents.size();
        qDebug() << "outputting old file array";
        qDebug() << file_byte_array[5] << file_byte_array.size();
        for (int i=0; i<=file_byte_array.size(); i++)
        {
            if (file_byte_array[i] != new_contents[i])
            {
                return_what = true;
                break;
            }
            else if (i == file_byte_array.size())
            {
                qDebug() << "compareDownload will return false, duplicate file.";
                return_what = false;
            }
        }
    }
    else
    {
        qDebug() << "compareDownload will return true, DNE.";
        return_what = true;
    }
    return return_what;
}

qDebug() 函数的输出是:

I am in compareDownload
outputting new file array
T 64704
outputting old file array
T 64576

【问题讨论】:

    标签: c++ qt qfile qbytearray


    【解决方案1】:

    读了几个小时的api,我找到了字节不同的原因。

    file.open(QIODevice::ReadOnly | QIODevice::Text);
    

    QIODevice::Text 需要删除。此标志将行尾终止符更改为 cpp 的终止符“\n”,从而给出字节差异。

    【讨论】:

      猜你喜欢
      • 2015-05-11
      • 2018-02-25
      • 2016-01-14
      • 2016-10-05
      • 2019-02-08
      • 2011-10-13
      • 2015-01-28
      • 2018-10-19
      • 2019-11-11
      相关资源
      最近更新 更多