c++ - 在 C++ 中使用 libcurl 下载多个文件

标签 c++ file download libcurl

我目前正在尝试为我的软件项目制作一个更新程序。我需要它才能下载多个文件,我不介意它们是同步下载还是一个接一个地下载,哪个更容易(文件大小不是问题)。我按照 libcurl 网页和其他一些资源中的示例进行了操作,得出了以下结论:

#include <iostream>
#include <stdio.h>
#include <curl/curl.h>
#include <string.h>
size_t write_data(void *ptr, size_t size, size_t nmemb, FILE *stream) {
    size_t written;
    written = fwrite(ptr, size, nmemb, stream);
    return written;
}
int main(void){
    for (int i = 0; i < 2;){        //download 2 files (loop twice)
        CURL *curl;
        FILE *fp;
        CURLcode res;
        char *url = "http://sec7.org/1024kb.txt";  //first file URL
        char outfilename[FILENAME_MAX] = "C:\\users\\grant\\desktop\\1024kb.txt";
        curl = curl_easy_init();
        if (curl){
            fp = fopen(outfilename,"wb");
            curl_easy_setopt(curl, CURLOPT_URL, url);
            curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data);
            curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp);
            res = curl_easy_perform(curl);
            curl_easy_cleanup(curl);
            fclose(fp);
        }
         url = "http://sec7.org/index.html"; //I want to get a new file this time
         outfilename[FILENAME_MAX] = "C:\\users\\grant\\desktop\\index.html";

    }
    return 0;
}

第一个问题是,如果我删除新文件分配 (*url = "http://...") 并尝试循环下载代码两次,程序就会停止响应.这发生在程序中多次调用下载的任意组合中。另一个问题是我无法更改字符数组 outfilename[FILENAME_MAX] 的值。我觉得这只是我犯的一些愚蠢的错误,但没有想到解决方案。谢谢!

最佳答案

  1. 为什么不把它放在一个函数中并调用它两次?

  2. 您的数组语法完全错误,而且循环内的所有变量都是局部变量,这意味着它们在每次循环迭代后都会被销毁。

  3. Conspicuous Compiler 所说的内容。这就是导致您的程序卡住的原因;它陷入了无限循环,因为 i 永远不会是 > 2

像这样将您的代码放入函数中:

void downloadFile(const char* url, const char* fname) {
    CURL *curl;
    FILE *fp;
    CURLcode res;
    curl = curl_easy_init();
    if (curl){
        fp = fopen(fname, "wb");
        curl_easy_setopt(curl, CURLOPT_URL, url);
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data);
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp);
        res = curl_easy_perform(curl);
        curl_easy_cleanup(curl);
        fclose(fp);
    }
}

并使用相关的文件名和 url 调用它两次:

downloadFile("http://sec7.org/1024kb.txt", "C:\\users\\grant\\desktop\\1024kb.txt");
downloadFile("http://sec7.org/index.html", "C:\\users\\grant\\desktop\\index.html");

虽然示例函数非常糟糕,但它只是一个示例。您应该更改它以返回错误代码/抛出异常,以及类似的东西。

关于c++ - 在 C++ 中使用 libcurl 下载多个文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6951161/

相关文章:

C++ Google 风格 : Automatic correction

c++ - 贝尔曼福特邻接矩阵的单源最短路径未检测到负循环

c++ - 通过引用传递 vector 并在基于范围的 for 循环中更改其值?

Java - 读取工资并获取总计

swift - 在后台下载并在完成后唤醒应用程序

http - 为什么通过 wget 的 HTTP 传输比 lftp/pget 更快?

c++ - OpenCV - moments() 函数中的参数

javascript - 无需服务器端编码的文件操作

java - Android Studio : Can't write to external storage?

azure - 哪里可以下载 WindowsAzure SDK 1.8