Executable getting somehow corrupted when being copied

蓝咒 提交于 2019-12-02 00:52:01

When writing a byte array to a QDataStream, the array's length is written as well.

Simply don't use the data stream, use QFile, or, better QTemporaryFile directly.

The example below demonstrates how to leverage C++11 and Qt 5 to make it really simple:

Writing to: /var/folders/yy/2tl/T/download-29543601.L91178
Wrote  55015 bytes.
Downloaded 55015 of -1 bytes
Wrote  7572 bytes.
Wrote  6686 bytes.
Wrote  5104 bytes.
Downloaded 74377 of 74377 bytes
Successfully wrote /var/folders/yy/2tl/T/download-29543601.L91178
#include <QCoreApplication>
#include <QNetworkAccessManager>
#include <QNetworkReply>
#include <QTemporaryFile>
#include <QUrl>
#include <QByteArray>
#include <QTextStream>
#include <QDebug>
#include <cstdio>

QTextStream out(stdout);
QTextStream in(stdin);

int main(int argc, char *argv[])
{
   QCoreApplication a(argc, argv);
   QNetworkAccessManager mgr;

   auto url = QUrl("http://stackoverflow.com/questions/29543601/"
                   "executable-getting-somehow-corrupted-when-being-copied");
   auto reply = mgr.get(QNetworkRequest(url));

   QTemporaryFile file;
   if (!file.open()) {
      qDebug() << "Can't open file for writing.";
      return -1;
   }
   out << "Writing to: " << file.fileName() << endl;

   QObject::connect(reply, &QNetworkReply::downloadProgress, [](qint64 rx, qint64 total) {
      qDebug() << "Downloaded" << rx << "of" << total << "bytes";
   });

   QObject::connect(reply, &QIODevice::readyRead, [reply, &file]{
      auto data = reply->readAll();
      auto written = file.write(data);
      if (data.size() != written) {
         qDebug() << "Write failed, wrote" << written << "out of" << data.size() << "bytes.";
      } else {
         qDebug() << "Wrote " << written << "bytes.";
      }
   });

   QObject::connect(reply, &QNetworkReply::finished, [reply, &file]{
      if (reply->error() != QNetworkReply::NoError) {
         qDebug() << "The request was unsuccessful. Error:" << reply->error();
         qApp->quit();
         return;
      }
      if (file.flush()) {
         out << "Successfully wrote " << file.fileName();
         out << "\nPress Enter to remove the file and exit." << flush;
         in.readLine();
      } else {
         qDebug() << "The file flush has failed";
      }
      qApp->quit();
   });

   return a.exec();
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!