【发布时间】: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++,但我在发布问题之前忘记添加它。