gpt4 book ai didi

c++ - 仅在res == 0时才使用C++ Curl下载吗?

转载 作者:行者123 更新时间:2023-12-03 08:53:17 25 4
gpt4 key购买 nike

我正在使用此代码从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,如何只显示最终文件,如果不显示错误消息,请退出应用程序。 ?

谢谢

最佳答案

我认为您不应使用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给定的回调的数据

关于c++ - 仅在res == 0时才使用C++ Curl下载吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35597827/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com