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

标签 c++ curl error-handling libcurl

我正在使用此代码从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/

相关文章:

c++ - mxGetPr() 的返回值——等效循环

tsql - 如何有条件地从通过SQLCMD运行的SQL代码中退出.BAT文件

c++ - C++-标准输入循环

c++ - 在 C++ 中包含文件错误

c++ - 我应该用什么代替 cl::KernelFunctor?

c++ - C++ 中的动态数据类型转换

javascript - 将 json 数据从客户端发送到 Marklogic Server 机器

python - 将此 curl 命令转换为 Python 3

macos - 使用 bash 从 URL 获取 youtube 视频时长

ruby-on-rails - Rails - 从模型中获取不是验证错误的错误消息