ftpgetresp.c (2682B)
1 /*************************************************************************** 2 * _ _ ____ _ 3 * Project ___| | | | _ \| | 4 * / __| | | | |_) | | 5 * | (__| |_| | _ <| |___ 6 * \___|\___/|_| \_\_____| 7 * 8 * Copyright (C) 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.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 * SPDX-License-Identifier: curl 22 * 23 ***************************************************************************/ 24 #include <stdio.h> 25 26 #include <curl/curl.h> 27 28 /* <DESC> 29 * Similar to ftpget.c but also stores the received response-lines 30 * in a separate file using our own callback! 31 * </DESC> 32 */ 33 static size_t 34 write_response(void *ptr, size_t size, size_t nmemb, void *data) 35 { 36 FILE *writehere = (FILE *)data; 37 return fwrite(ptr, size, nmemb, writehere); 38 } 39 40 #define FTPBODY "ftp-list" 41 #define FTPHEADERS "ftp-responses" 42 43 int main(void) 44 { 45 CURL *curl; 46 CURLcode res; 47 FILE *ftpfile; 48 FILE *respfile; 49 50 /* local filename to store the file as */ 51 ftpfile = fopen(FTPBODY, "wb"); /* b is binary, needed on Windows */ 52 if(!ftpfile) 53 return 1; 54 55 /* local filename to store the FTP server's response lines in */ 56 respfile = fopen(FTPHEADERS, "wb"); /* b is binary, needed on Windows */ 57 if(!respfile) { 58 fclose(ftpfile); 59 return 1; 60 } 61 62 curl = curl_easy_init(); 63 if(curl) { 64 /* Get a file listing from sunet */ 65 curl_easy_setopt(curl, CURLOPT_URL, "ftp://ftp.example.com/"); 66 curl_easy_setopt(curl, CURLOPT_WRITEDATA, ftpfile); 67 /* If you intend to use this on Windows with a libcurl DLL, you must use 68 CURLOPT_WRITEFUNCTION as well */ 69 curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, write_response); 70 curl_easy_setopt(curl, CURLOPT_HEADERDATA, respfile); 71 res = curl_easy_perform(curl); 72 /* Check for errors */ 73 if(res != CURLE_OK) 74 fprintf(stderr, "curl_easy_perform() failed: %s\n", 75 curl_easy_strerror(res)); 76 77 /* always cleanup */ 78 curl_easy_cleanup(curl); 79 } 80 81 fclose(ftpfile); /* close the local file */ 82 fclose(respfile); /* close the response file */ 83 84 return 0; 85 }