ftpget.c 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. /*****************************************************************************
  2. * _ _ ____ _
  3. * Project ___| | | | _ \| |
  4. * / __| | | | |_) | |
  5. * | (__| |_| | _ <| |___
  6. * \___|\___/|_| \_\_____|
  7. *
  8. * $Id$
  9. */
  10. #include <stdio.h>
  11. #include <curl/curl.h>
  12. #include <curl/types.h>
  13. #include <curl/easy.h>
  14. /*
  15. * This is an example showing how to get a single file from an FTP server.
  16. * It delays the actual destination file creation until the first write
  17. * callback so that it won't create an empty file in case the remote file
  18. * doesn't exist or something else fails.
  19. */
  20. struct FtpFile {
  21. const char *filename;
  22. FILE *stream;
  23. };
  24. static size_t my_fwrite(void *buffer, size_t size, size_t nmemb, void *stream)
  25. {
  26. struct FtpFile *out=(struct FtpFile *)stream;
  27. if(out && !out->stream) {
  28. /* open file for writing */
  29. out->stream=fopen(out->filename, "wb");
  30. if(!out->stream)
  31. return -1; /* failure, can't open file to write */
  32. }
  33. return fwrite(buffer, size, nmemb, out->stream);
  34. }
  35. int main(void)
  36. {
  37. CURL *curl;
  38. CURLcode res;
  39. struct FtpFile ftpfile={
  40. "curl.tar.gz", /* name to store the file as if succesful */
  41. NULL
  42. };
  43. curl_global_init(CURL_GLOBAL_DEFAULT);
  44. curl = curl_easy_init();
  45. if(curl) {
  46. /*
  47. * Get curl 7.9.2 from sunet.se's FTP site. curl 7.9.2 is most likely not
  48. * present there by the time you read this, so you'd better replace the
  49. * URL with one that works!
  50. */
  51. curl_easy_setopt(curl, CURLOPT_URL,
  52. "ftp://ftp.sunet.se/pub/www/utilities/curl/curl-7.9.2.tar.gz");
  53. /* Define our callback to get called when there's data to be written */
  54. curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, my_fwrite);
  55. /* Set a pointer to our struct to pass to the callback */
  56. curl_easy_setopt(curl, CURLOPT_WRITEDATA, &ftpfile);
  57. /* Switch on full protocol/debug output */
  58. curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L);
  59. res = curl_easy_perform(curl);
  60. /* always cleanup */
  61. curl_easy_cleanup(curl);
  62. if(CURLE_OK != res) {
  63. /* we failed */
  64. fprintf(stderr, "curl told us %d\n", res);
  65. }
  66. }
  67. if(ftpfile.stream)
  68. fclose(ftpfile.stream); /* close the local file */
  69. curl_global_cleanup();
  70. return 0;
  71. }