我目前正在尝试为我的软件项目制作更新程序。我需要它能够下载多个文件,我不介意他们是同步下载还是一个接一个地下载,无论哪种更容易(文件大小不是问题)。我按照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]
的值。我觉得这只是我正在做的一些愚蠢的错误,但没有想到解决方案。谢谢!
答案 0 :(得分:4)
为什么不把它放在一个函数中并调用它两次?
你的数组语法都是错误的,而且循环中的所有变量都是本地的,这意味着它们在每次循环迭代后都会被销毁。
显眼的编译器说。这就是导致程序冻结的原因;它被困在一个无限循环中,因为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);
}
}
用相关的文件名和网址调用两次:
downloadFile("http://sec7.org/1024kb.txt", "C:\\users\\grant\\desktop\\1024kb.txt");
downloadFile("http://sec7.org/index.html", "C:\\users\\grant\\desktop\\index.html");
示例函数非常糟糕,但它只是一个例子。您应该更改它以返回错误代码/抛出异常,以及类似的东西。