【问题标题】:Downloading multiple files with libcurl in C++在 C++ 中使用 libcurl 下载多个文件
【发布时间】:2011-08-05 03:46:11
【问题描述】:

我目前正在尝试为我的软件项目制作更新程序。我需要它能够下载多个文件,我不介意它们是同步下载还是一个接一个地下载,无论哪个更容易(文件大小不是问题)。我遵循了 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] 的值。我觉得这只是我犯的一些愚蠢的错误,但没有想到任何解决方案。谢谢!

【问题讨论】:

  • 老兄,你的for循环需要i++
  • 我的错,我试图实现其他东西而不是 i++,但我在发布问题之前忘记添加它。

标签: c++ file download libcurl


【解决方案1】:
  1. 为什么不把它放在一个函数中并调用两次呢?

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

  3. 显着编译器所说的。这就是导致您的程序冻结的原因;它陷入了无限循环,因为i 永远不是&gt; 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);
    }
}

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

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

虽然示例功能很糟糕,但它只是一个示例。您应该更改它以返回错误代码/抛出异常等。

【讨论】:

  • 哈哈,谢谢。有时我太着迷于修复小错误,以至于忘记了简化并将事情放在函数中。非常感谢 Seth 的回复,我将详细说明代码并进行一些错误处理。
猜你喜欢
  • 2010-12-10
  • 2011-01-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多