我是使用此代码从Web服务器下载文件,这是有效的,在此处获得一些帮助后,我现在收到错误代码。这是我正在使用的代码:
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);
curl_easy_setopt(curl, CURLOPT_FAILONERROR, true);
res = curl_easy_perform(curl);
cout << res;
if (res != 0) {
cout << curl_easy_strerror(res);
return;
}
curl_easy_cleanup(curl);
fclose(fp);
}
}
我正在尝试的只是在res
为0时才创建本地文件,否则显示错误代码并停止应用程序。
到目前为止,我尝试过的所有内容都会导致创建一个文件,并且通常会包含来自服务器的返回信息。
如果res
= 0,如何不显示错误消息并退出应用程序,我该如何才创建最终文件。 ?
由于
答案 0 :(得分:0)
我认为你不应该使用write_data
写函数,而应该使用自定义函数:
size_t store_content(char *ptr, size_t size, size_t nmemb, void *userdata)
{
std::string &content = static_cast<std::string>(*userdata);
content += std::string(ptr, size*nmemb);
return size*nmemb;
}
void downloadFile(const char* url, const char* fname) {
CURL *curl;
FILE *fp;
CURLcode res;
std::string content;
curl = curl_easy_init();
if (curl){
curl_easy_setopt(curl, CURLOPT_URL, url);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, store_content);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &content);
curl_easy_setopt(curl, CURLOPT_FAILONERROR, true);
res = curl_easy_perform(curl);
if (res != 0) {
fp = fopen(fname, "wb"); // TODO: check errors
fwrite(content.data(), content.size(), 1, fp); // TODO: check errors
fclose(fp);
}
curl_easy_cleanup(curl);
}
}
CURLOPT_WRITEFUNCTION
用于设置libcurl收到数据时调用的函数。
CURLOPT_WRITEDATA
用于设置指向您希望传递给CURLOPT_WRITEFUNCTION