3c3888a20f52b5ae5fab369409999506e4c79660
[external/curl.git] / docs / examples / ftpget.c
1 /*****************************************************************************
2  *                                  _   _ ____  _
3  *  Project                     ___| | | |  _ \| |
4  *                             / __| | | | |_) | |
5  *                            | (__| |_| |  _ <| |___
6  *                             \___|\___/|_| \_\_____|
7  *
8  */
9
10 #include <stdio.h>
11
12 #include <curl/curl.h>
13 #include <curl/types.h>
14 #include <curl/easy.h>
15
16 /*
17  * This is an example showing how to get a single file from an FTP server.
18  * It delays the actual destination file creation until the first write
19  * callback so that it won't create an empty file in case the remote file
20  * doesn't exist or something else fails.
21  */
22
23 struct FtpFile {
24   const char *filename;
25   FILE *stream;
26 };
27
28 static size_t my_fwrite(void *buffer, size_t size, size_t nmemb, void *stream)
29 {
30   struct FtpFile *out=(struct FtpFile *)stream;
31   if(out && !out->stream) {
32     /* open file for writing */
33     out->stream=fopen(out->filename, "wb");
34     if(!out->stream)
35       return -1; /* failure, can't open file to write */
36   }
37   return fwrite(buffer, size, nmemb, out->stream);
38 }
39
40
41 int main(void)
42 {
43   CURL *curl;
44   CURLcode res;
45   struct FtpFile ftpfile={
46     "curl.tar.gz", /* name to store the file as if succesful */
47     NULL
48   };
49
50   curl_global_init(CURL_GLOBAL_DEFAULT);
51
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/pub/www/utilities/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
64     /* Switch on full protocol/debug output */
65     curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L);
66
67     res = curl_easy_perform(curl);
68
69     /* always cleanup */
70     curl_easy_cleanup(curl);
71
72     if(CURLE_OK != res) {
73       /* we failed */
74       fprintf(stderr, "curl told us %d\n", res);
75     }
76   }
77
78   if(ftpfile.stream)
79     fclose(ftpfile.stream); /* close the local file */
80
81   curl_global_cleanup();
82
83   return 0;
84 }