url2file.c 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. /***************************************************************************
  2. * _ _ ____ _
  3. * Project ___| | | | _ \| |
  4. * / __| | | | |_) | |
  5. * | (__| |_| | _ <| |___
  6. * \___|\___/|_| \_\_____|
  7. *
  8. * Copyright (C) 1998 - 2019, 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 https://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. /* <DESC>
  23. * Download a given URL into a local file named page.out.
  24. * </DESC>
  25. */
  26. #include <stdio.h>
  27. #include <stdlib.h>
  28. //#include <unistd.h>
  29. #include "curl/curl.h"
  30. static size_t write_data(void *ptr, size_t size, size_t nmemb, void *stream)
  31. {
  32. size_t written = fwrite(ptr, size, nmemb, (FILE *)stream);
  33. return written;
  34. }
  35. int main(int argc, char *argv[])
  36. {
  37. CURL *curl_handle;
  38. // sets file name to page.out
  39. static const char *pagefilename = "page.out";
  40. FILE *pagefile;
  41. // if the number of arguments passed to the curl function is less than 2. it fails.
  42. if(argc < 2) {
  43. printf("Usage: %s <URL>\n", argv[0]);
  44. return 1;
  45. }
  46. curl_global_init(CURL_GLOBAL_ALL);
  47. /* init the curl session */
  48. curl_handle = curl_easy_init();
  49. /* set URL to get here */
  50. curl_easy_setopt(curl_handle, CURLOPT_URL, argv[1]);
  51. /* Switch on full protocol/debug output while testing */
  52. curl_easy_setopt(curl_handle, CURLOPT_VERBOSE, 1L);
  53. /* disable progress meter, set to 0L to enable it */
  54. curl_easy_setopt(curl_handle, CURLOPT_NOPROGRESS, 1L);
  55. /* send all data to this function */
  56. curl_easy_setopt(curl_handle, CURLOPT_WRITEFUNCTION, write_data);
  57. /* open the file */
  58. pagefile = fopen(pagefilename, "wb");
  59. if(pagefile) {
  60. /* write the page body to this file handle */
  61. curl_easy_setopt(curl_handle, CURLOPT_WRITEDATA, pagefile);
  62. /* get it! */
  63. curl_easy_perform(curl_handle);
  64. /* close the header file */
  65. fclose(pagefile);
  66. }
  67. /* cleanup curl stuff */
  68. curl_easy_cleanup(curl_handle);
  69. curl_global_cleanup();
  70. return 0;
  71. }