#curl CURLOPT_XFERINFOFUNCTION doesn't work

4 messages · Page 1 of 1 (latest)

lusty shard
#

So, im using simple curl c++ script to download file

bool downloadFile(const char* url) {
    CURL* curl;
    CURLcode res;

    const char *filename = "out.txt";


    FILE* fp = fopen(filename, "wb");
    if (fp == NULL) {
        std::cerr << "Failed to open file for writing" << std::endl << "File name: " << getFileNameFromUrl(url) << std::endl;
        std::perror("fopen");
        return false;
    }

    curl = curl_easy_init();
    if (curl) {
        curl_easy_setopt(curl, CURLOPT_URL, url);

        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data);
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp);

        DownloadProgress data;
        data.start_time = std::chrono::steady_clock::now();
        data.fp = fp;
        curl_easy_setopt(curl, CURLOPT_XFERINFODATA, &data);
        curl_easy_setopt(curl, CURLOPT_XFERINFOFUNCTION, progress_callback);
        

        res = curl_easy_perform(curl);
        if (res != CURLE_OK) {
            std::cerr << "Failed to download: " << curl_easy_strerror(res) << std::endl;
            fclose(fp);
            curl_easy_cleanup(curl);
            return false;
        }

        curl_easy_cleanup(curl);
    }

    fclose(fp);
    return true;
}

But my CURLOPT_XFERINFOFUNCTION doesn't call at all:

int progress_callback(void* clientp, curl_off_t dltotal, curl_off_t dlnow, curl_off_t ultotal, curl_off_t ulnow) {
    std::cout << "Started downloading\n";
    double progress = (dlnow / (double)dltotal) * 100;
    auto elapsed_seconds = std::chrono::duration_cast<std::chrono::seconds>(std::chrono::steady_clock::now() - ((DownloadProgress*)clientp)->start_time).count();
    std::cout << dlnow / 1024 << "/" << dltotal / 1024 << " KB [" << std::string(progress / 2, '|') << std::string(50 - progress / 2, '_') << "] | Speed: " << (dlnow / 1024) / elapsed_seconds << " KB/s | Elapsed Time: " << elapsed_seconds << "s" << std::flush;
    return 0;
}
toxic grottoBOT
#

When your question is answered use !solved to mark the question as resolved.

Remember to ask specific questions, provide necessary details, and reduce your question to its simplest form. For tips on how to ask a good question use !howto ask.

lusty shard
#

Output im getting:

Downloaded!
Press any key to continue...

Expected:

Progress bar here
Downloaded!
Press any key to continue...
lusty shard
#

!solved