libcurl错误,curl_easy_perform()失败:c ++

时间:2016-05-13 06:52:41

标签: c++ curl libcurl

我已经使用libcurl编写了下载文件的代码:

#ifndef CHECK_RESOURCES_H
#define CHECK_RESOURCES_H

#include <string>
#include <stdio.h>
#include <curl/curl.h>
// #include <bzlib.h>


void progress_bar (void* ptr, double TotalToDownload, double NowDownloaded, \
    double TotalToUpload, double NowUploaded) {

    printf("%f : %f \n", TotalToDownload, NowDownloaded);
}

void download_file () {
    CURL *curl;
    CURLcode res;
    char outFileName[FILENAME_MAX] = "shape_predictor_68_face_landmarks.dat.bz2";
    std::string url = "http://ufpr.dl.sourceforge.net/project/dclib/dlib/v18.10/shape_predictor_68_face_landmarks.dat.bz2";
    FILE *fp;

    curl = curl_easy_init ();
    if (curl) {
        fp = fopen (outFileName, "wb");

        curl_easy_setopt (curl, CURLOPT_URL, url.c_str());
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, NULL);
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp);

        // Internal CURL progressmeter must be disabled if we provide our own callback
        curl_easy_setopt(curl, CURLOPT_NOPROGRESS, false);
        // Install the callback function
        curl_easy_setopt(curl, CURLOPT_PROGRESSFUNCTION, progress_bar);

        res = curl_easy_perform (curl);

        if (res != CURLE_OK) {
            fprintf(stderr, "%s%s\n", "curl_easy_perform() failed : ", curl_easy_strerror(res));
        }

        curl_easy_cleanup (curl);
        fclose (fp);
    }
}

void extract_bz2 () {

}


void check_dlib_landmark_weights (const std::string& name) {
    if (FILE *file = fopen(name.c_str(), "r")) {
        fclose(file);
    } else {
        download_file ();
    }
}


#endif  // CHECK_RESOURCES_H

问题是,当我运行代码时,它会给出这个输出:

0.000000 : 0.000000 
0.000000 : 0.000000 
curl_easy_perform() failed : Operation was aborted by an application callback

我不明白为什么会失败。我已经检查了我正在使用的链接,这是一个工作链接(没有任何问题下载文件)。我该如何纠正?

1 个答案:

答案 0 :(得分:4)

CURLOPT_PROGRESSFUNCTION期望回调函数返回值0,目前函数返回void。如果您修改progress_bar函数以返回int而不是void,并将return 0;添加到应该解决问题的末尾。