Source Code File 05-03_ftpfile1.c
#include <stdio.h> #include <stdlib.h> #include <sys/stat.h> #include <curl/curl.h> static size_t read_callback( void *ptr, size_t size, size_t nmemb, void *user_data) { FILE *local_fp; size_t r; /* initialize local pointer */ local_fp = (FILE *)user_data; /* read a chunk from the file */ r = fread(ptr, size, nmemb, local_fp); return(r); } int main() { char ftp_upload[] = "ftp://127.0.0.0/image1.jpg"; char user_pass[] = "username:password"; char upload_filename[] = "image1.jpg"; CURL *curl; CURLcode res; FILE *input; struct stat finfo; int file_size; /* get the file size */ stat(upload_filename, &finfo); file_size = finfo.st_size; /* open the file */ input = fopen( upload_filename, "rb"); if( input==NULL) { fprintf(stderr, "Unable to read from %s\n", upload_filename); exit(1); } /* initialize curl */ curl = curl_easy_init(); puts("Preparing FTP..."); /* set options for FPT upload */ curl_easy_setopt(curl, CURLOPT_URL, ftp_upload); curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L); curl_easy_setopt(curl, CURLOPT_USERPWD, user_pass); curl_easy_setopt(curl, CURLOPT_UPLOAD, 1L); curl_easy_setopt(curl, CURLOPT_INFILESIZE_LARGE, (curl_off_t)file_size); curl_easy_setopt(curl, CURLOPT_READFUNCTION, read_callback); curl_easy_setopt(curl, CURLOPT_READDATA, input); /* request-send upload */ res = curl_easy_perform(curl); if( res!=CURLE_OK ) { fprintf(stderr, "curl upload failed: %s\n", curl_easy_strerror(res)); fclose(input); exit(1); } /* cleanup */ curl_easy_cleanup(curl); fclose(input); /* inform the user */ puts("FTP upload complete"); return(0); }
Notes
* The ftp_upload[] string is a placeholder. Replace it with a legitimate FTP server name and filename appended.
* The user_pass[] string is also a placeholder.
* Ensure that the upload_filename[] string references a valid file on the local system.
* Wide version of this code (statements not split)
Copyright © 1997-2024 by QPBC.
All rights reserved