C++ libcurl控制台进度条

8 c++ console libcurl progress-bar

我希望在下载文件时在控制台窗口中显示进度条.我的代码是这样的:在C/C++中使用libcurl下载文件.

如何在libcurl中有进度条?

fvu*_*fvu 16

你的仪表.

int progress_func(void* ptr, double TotalToDownload, double NowDownloaded, 
                    double TotalToUpload, double NowUploaded)
{
    // ensure that the file to be downloaded is not empty
    // because that would cause a division by zero error later on
    if (TotalToDownload <= 0.0)) {
        return 0;
    }

    // how wide you want the progress meter to be
    int totaldotz=40;
    double fractiondownloaded = NowDownloaded / TotalToDownload;
    // part of the progressmeter that's already "full"
    int dotz = round(fractiondownloaded * totaldotz);

    // create the "meter"
    int ii=0;
    printf("%3.0f%% [",fractiondownloaded*100);
    // part  that's full already
    for ( ; ii < dotz;ii++) {
        printf("=");
    }
    // remaining part (spaces)
    for ( ; ii < totaldotz;ii++) {
        printf(" ");
    }
    // and back to line begin - do not forget the fflush to avoid output buffering problems!
    printf("]\r");
    fflush(stdout);
    // if you don't return 0, the transfer will be aborted - see the documentation
    return 0; 
}
Run Code Online (Sandbox Code Playgroud)


fvu*_*fvu 10

curl文档

CURLOPT_PROGRESSFUNCTION

应该与找到的curl_progress_callback原型匹配的函数指针.无论数据是否被传输,此函数都会被libcurl而不是其内部等效函数调用,在运行期间(大约每秒一次)频繁间隔.传递给回调的未知/未使用参数值将设置为零(如果只下载数据,则上载大小将保持为0).从此回调返回非零值将导致libcurl中止传输并返回CURLE_ABORTED_BY_CALLBACK.

所以:

您提供了这样的功能

int progress_func(void* ptr, double TotalToDownload, double NowDownloaded, double TotalToUpload, double NowUploaded)
{
    // It's here you will write the code for the progress message or bar
}
Run Code Online (Sandbox Code Playgroud)

现有选项之后的一些额外选项

curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp);  // already there
// 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_func); 
Run Code Online (Sandbox Code Playgroud)

这就是所有需要做的事情

  • @ user1089679确保你的回调中返回0 (2认同)