progressfunc.c 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. /***************************************************************************
  2. * _ _ ____ _
  3. * Project ___| | | | _ \| |
  4. * / __| | | | |_) | |
  5. * | (__| |_| | _ <| |___
  6. * \___|\___/|_| \_\_____|
  7. *
  8. * Copyright (C) 1998 - 2011, Daniel Stenberg, <daniel@haxx.se>, et al.
  9. *
  10. * This software is licensed as described in the file COPYING, which
  11. * you should have received as part of this distribution. The terms
  12. * are also available at http://curl.haxx.se/docs/copyright.html.
  13. *
  14. * You may opt to use, copy, modify, merge, publish, distribute and/or sell
  15. * copies of the Software, and permit persons to whom the Software is
  16. * furnished to do so, under the terms of the COPYING file.
  17. *
  18. * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
  19. * KIND, either express or implied.
  20. *
  21. ***************************************************************************/
  22. #include <stdio.h>
  23. #include <curl/curl.h>
  24. #define STOP_DOWNLOAD_AFTER_THIS_MANY_BYTES 6000
  25. #define MINIMAL_PROGRESS_FUNCTIONALITY_INTERVAL 3
  26. struct myprogress {
  27. double lastruntime;
  28. CURL *curl;
  29. };
  30. static int progress(void *p,
  31. double dltotal, double dlnow,
  32. double ultotal, double ulnow)
  33. {
  34. struct myprogress *myp = (struct myprogress *)p;
  35. CURL *curl = myp->curl;
  36. double curtime = 0;
  37. curl_easy_getinfo(curl, CURLINFO_TOTAL_TIME, &curtime);
  38. /* under certain circumstances it may be desirable for certain functionality
  39. to only run every N seconds, in order to do this the transaction time can
  40. be used */
  41. if((curtime - myp->lastruntime) >= MINIMAL_PROGRESS_FUNCTIONALITY_INTERVAL) {
  42. myp->lastruntime = curtime;
  43. fprintf(stderr, "TOTAL TIME: %f \r\n", curtime);
  44. }
  45. fprintf(stderr, "UP: %g of %g DOWN: %g of %g\r\n",
  46. ulnow, ultotal, dlnow, dltotal);
  47. if(dlnow > STOP_DOWNLOAD_AFTER_THIS_MANY_BYTES)
  48. return 1;
  49. return 0;
  50. }
  51. int main(void)
  52. {
  53. CURL *curl;
  54. CURLcode res=0;
  55. struct myprogress prog;
  56. curl = curl_easy_init();
  57. if(curl) {
  58. prog.lastruntime = 0;
  59. prog.curl = curl;
  60. curl_easy_setopt(curl, CURLOPT_URL, "http://example.com/");
  61. curl_easy_setopt(curl, CURLOPT_PROGRESSFUNCTION, progress);
  62. /* pass the struct pointer into the progress function */
  63. curl_easy_setopt(curl, CURLOPT_PROGRESSDATA, &prog);
  64. curl_easy_setopt(curl, CURLOPT_NOPROGRESS, 0L);
  65. res = curl_easy_perform(curl);
  66. if(res)
  67. fprintf(stderr, "%s\n", curl_easy_strerror(res));
  68. /* always cleanup */
  69. curl_easy_cleanup(curl);
  70. }
  71. return (int)res;
  72. }