#include<sys/stat.h>
#include<curl/curl.h>
#include<errno.h>
#include<stdlib.h>
#include<string.h>
#include<unistd.h>
/*
上傳文件url爲 ftp://192.168.1.100/ftp/text.txt 路徑根據需要改
*/
static size_t upload_content(void *ptr,size_t size,size_t nmemb,void *stream)
{
static int i=0;
char **content=(char **)stream;
if((size == 0) || (nmemb == 0) || ((size*nmemb) < 1)) {
return 0;
}
const char *date=content[i];
if(date){
size_t len=strlen(date);
memcpy(ptr,date,len);
i++;
return len;
}
return 0;
}
int ftp_upload(char* file_prefix, char* file_content, char* file_suffix, char* username, char* password)
{
char *FTP_URL="ftp://192.168.1.100/ftp/";
int length=strlen(FTP_URL)+strlen(file_prefix)+strlen(file_suffix)+1;
char *REMOTE_URL=(char *)malloc(length);
sprintf(REMOTE_URL,"%s%s%s",FTP_URL,file_prefix,file_suffix);
CURL *curl;
CURLcode res;
curl_global_init(CURL_GLOBAL_ALL);
curl=curl_easy_init();
char *file_content_format=(char*)malloc(strlen(file_content)+strlen("\r\n")+1);
sprintf(file_content_format,"%s%s",file_content,"\r\n");
char *content[]={
file_content_format,
NULL
};
if(curl){
curl_easy_setopt(curl,CURLOPT_READFUNCTION,upload_content);
curl_easy_setopt(curl,CURLOPT_UPLOAD,1L);
curl_easy_setopt(curl,CURLOPT_URL,REMOTE_URL);
curl_easy_setopt(curl,CURLOPT_USERNAME,username);
curl_easy_setopt(curl,CURLOPT_PASSWORD,password);
curl_easy_setopt(curl,CURLOPT_READDATA,content);
curl_easy_setopt(curl,CURLOPT_VERBOSE,1L);
res=curl_easy_perform(curl);
curl_easy_cleanup(curl);
if(res!=CURLE_OK){
fprintf(stderr,"\nerrno:%d\nerror message:",res);
printf("%s\n",curl_easy_strerror(res));
}
}
curl_global_cleanup();
}
int main(void)
{
ftp_upload("ts","asddsdddd咱",".txt","123","123"); //參數分別爲文件名,文件內容,文件類型,ftp用戶名,ftp密碼
return 0;
}