views:

29

answers:

1

Hi, 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?

+2  A: 

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.

Matthew Flaschen
This is for the progressbar, how can I use this to measure the speed?
Levo
Overall average download speed is dlnow/(current time - start time). "Current" download speed is a little trickier. First, you need to define what it means. One possibility is to have an old_time, and old_now. Then it is (dlnow - oldNow) / (current time - oldTime).
Matthew Flaschen