user197967
user197967

Reputation:

C libcurl - measure download speed and time remaining

I am using the following code to download files from the internet:

size_t write_data(void *ptr, size_t size, size_t nmemb, FILE *stream)
{
    size_t written;
    written = fwrite(ptr, size, nmemb, stream);
    return written;
}

int main(int argc, char** argv)
{
 FILE *downloaded_file;
 if ( (downloaded_file = fopen (download_path , "w" ) ) != NULL )
 {
  CURL *curl;
  CURLcode res;
  curl = curl_easy_init();
  if(curl)
  {
   curl_easy_setopt(curl, CURLOPT_URL, "www.asd.com/files/file_to_download.rar");
   curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data);
   curl_easy_setopt(curl, CURLOPT_WRITEDATA, downloaded_file);
   res = curl_easy_perform(curl);
   curl_easy_cleanup(curl);

   if (res == CURLE_OK)
   {
    printf("Download complete!\n");
   }
  }
  fclose(downloaded_file);
 }
}

How can I measure the current download speed (e.g. every second) and the remaining time to complete the download?

Upvotes: 2

Views: 3781

Answers (2)

T.H.
T.H.

Reputation: 876

CURLOPT_PROGRESSFUNCTION has been deprecated since v7.32.0, instead you can use CURLOPT_XFERINFOFUNCTION, the usage and callback structure (all the arguments dltotal, dlnow ...etc) are almost the same as CURLOPT_PROGRESSFUNCTION

Upvotes: 0

Matthew Flaschen
Matthew Flaschen

Reputation: 284826

You can use CURLOPT_PROGRESSFUNCTION. curl will pass 5 arguments to your callback function, clientp, dltotal, dlnow, ultotal, and ulnow. clientp is a pointer you provide with CURLOPT_PROGRESSDATA. The total parameters are the total amounts that need to be downloaded; the now ones are the amounts so far. Unknown values are 0.

To use this, you must set CURLOPT_NOPROGRESS to 0.

Upvotes: 7

Related Questions