ftpget.c 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  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. #include <stdio.h>
  23. #include <curl/curl.h>
  24. /* <DESC>
  25. * Get a single file from an FTP server.
  26. * </DESC>
  27. */
  28. struct FtpFile {
  29. const char *filename;
  30. FILE *stream;
  31. };
  32. static size_t my_fwrite(void *buffer, size_t size, size_t nmemb, void *stream)
  33. {
  34. struct FtpFile *out = (struct FtpFile *)stream;
  35. if(!out->stream) {
  36. /* open file for writing */
  37. out->stream = fopen(out->filename, "wb");
  38. if(!out->stream)
  39. return -1; /* failure, can't open file to write */
  40. }
  41. return fwrite(buffer, size, nmemb, out->stream);
  42. }
  43. int main(void)
  44. {
  45. CURL *curl;
  46. CURLcode res;
  47. struct FtpFile ftpfile = {
  48. "curl.tar.gz", /* name to store the file as if successful */
  49. NULL
  50. };
  51. curl_global_init(CURL_GLOBAL_DEFAULT);
  52. curl = curl_easy_init();
  53. if(curl) {
  54. /*
  55. * You better replace the URL with one that works!
  56. */
  57. curl_easy_setopt(curl, CURLOPT_URL,
  58. "ftp://ftp.example.com/curl/curl-7.9.2.tar.gz");
  59. /* Define our callback to get called when there's data to be written */
  60. curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, my_fwrite);
  61. /* Set a pointer to our struct to pass to the callback */
  62. curl_easy_setopt(curl, CURLOPT_WRITEDATA, &ftpfile);
  63. /* Switch on full protocol/debug output */
  64. curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L);
  65. res = curl_easy_perform(curl);
  66. /* always cleanup */
  67. curl_easy_cleanup(curl);
  68. if(CURLE_OK != res) {
  69. /* we failed */
  70. fprintf(stderr, "curl told us %d\n", res);
  71. }
  72. }
  73. if(ftpfile.stream)
  74. fclose(ftpfile.stream); /* close the local file */
  75. curl_global_cleanup();
  76. return 0;
  77. }