I would like a progress bar to appear in the console window while a file is being downloaded. My code is this: http://stackoverflow.com/questions/1636333/download-file-using-libcurl-in-c-c/1636827#1636827.
How to have a progress bar in libcurl?
I would like a progress bar to appear in the console window while a file is being downloaded. My code is this: http://stackoverflow.com/questions/1636333/download-file-using-libcurl-in-c-c/1636827#1636827.
How to have a progress bar in libcurl?
From the curl documentation
CURLOPT_PROGRESSFUNCTION
Function pointer that should match the curl_progress_callback prototype found in . This function gets called by libcurl instead of its internal equivalent with a frequent interval during operation (roughly once per second) no matter if data is being transfered or not. Unknown/unused argument values passed to the callback will be set to zero (like if you only download data, the upload size will remain 0). Returning a non-zero value from this callback will cause libcurl to abort the transfer and return CURLE_ABORTED_BY_CALLBACK.
So:
You provide a function that looks like this
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
}
And some extra options after the existing options
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);
That's all that needs to be done
Your meter.
int progress_func(void* ptr, double TotalToDownload, double NowDownloaded,
double TotalToUpload, double NowUploaded)
{
// 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);
}