Downloading File in Qt From URL

后端 未结 3 849
半阙折子戏
半阙折子戏 2020-12-31 17:43

In my program I need to download a file, and I came across this article:

http://www.java2s.com/Code/Cpp/Qt/DownloadfromURL.htm

This code does work but it d

3条回答
  •  隐瞒了意图╮
    2020-12-31 17:54

    As you asked for it, some general comments:

    void QtDownload::downloadFinished(QNetworkReply *data)
    {
        QFile localFile("downloadedfile");
        if (!localFile.open(QIODevice::WriteOnly))
            return;
        localFile.write(data->readAll());
        localFile.close();
        delete data;
        data = 0;
    }
    
    1. You read all data in one chunk. Bad for big files. Better read it incrementally.
    2. Deleting the argument data from a slot is dangerous. You don't know whether the network manager continues to use (or delete) the object "data" points to right after it emits the finished signal. Probably you don't even have to delete the reply, if its owned by the manager, something to check the documentation for.
    3. If opening the files fails, data is not deleted. So whatever is correct, its inconsistent. Either you leak or you have the risk of double-deletion.
    4. localFile.write(data->readAll()) is not guaranteed to write all data at once. that's why it has a return value, which you should check, to make sure everything is written. If it returns -1, you should handle the error.

      if (reply != 0)
          delete reply;
      

    Omit the if. Deleting a null pointer is safe.

提交回复
热议问题