#include <unistd.h> #include <stdlib.h> #include <stdio.h> #include <curl/curl.h> #include <string.h> int debugFun(CURL* curl, curl_infotype type, char* str, size_t len, void* stream) { //只打印CURLINFO_TEXT類型的信息 if(type == CURLINFO_TEXT) { fwrite(str, 1, len, (FILE*)stream); } } int main(int argc, char** argv) { CURL* curl; CURLcode res; char errorBuf[CURL_ERROR_SIZE]; FILE *sendFile, *debugFile; char ftpurl[256 + 1]; char usrpasswd[64 + 1]; curl_slist *slist=NULL; if(argc != 7) { printf("Usage:\n\t./ftp ip username password ftpPath destFileName srcFile"); return -1; } //將相關的調試信息打印到dubugFile.txt中 if(NULL == (debugFile = fopen("debugFile.txt", "a+"))) return -1; //打開ftp上傳的源文件 if(NULL == (sendFile = fopen(argv[6], "r"))) { fclose(debugFile); return -1; } //獲取需要發送文件的大小 fseek(sendFile, 0, SEEK_END); int sendSize = ftell(sendFile); if(sendSize < 0) { fclose(debugFile); fclose(sendFile); return -1; } fseek(sendFile, 0L, SEEK_SET); if((res = curl_global_init(CURL_GLOBAL_ALL)) != 0) { fclose(debugFile); fclose(sendFile); return -1; } if((curl = curl_easy_init()) == NULL) { fclose(debugFile); fclose(sendFile); curl_global_cleanup(); return -1; } if(argv[4][strlen(argv[4]) - 1] != '/') sprintf(ftpurl, "ftp://%s/%s/%s", argv[1], argv[4], argv[5]); else sprintf(ftpurl, "ftp://%s/%s%s", argv[1], argv[4], argv[5]); curl_easy_setopt(curl, CURLOPT_URL, ftpurl); //設置ftp上傳url,組成如下的URL //ftp://192.168.31.145//root/subdir/curl/testftp.txt sprintf(usrpasswd, "%s:%s", argv[2], argv[3]); curl_easy_setopt(curl, CURLOPT_USERPWD, usrpasswd); curl_easy_setopt(curl, CURLOPT_VERBOSE, 1); curl_easy_setopt(curl, CURLOPT_DEBUGDATA, debugFile); curl_easy_setopt(curl, CURLOPT_READDATA, sendFile); curl_easy_setopt(curl, CURLOPT_UPLOAD, 1); curl_easy_setopt(curl, CURLOPT_INFILESIZE, sendSize); curl_easy_setopt(curl, CURLOPT_FTP_CREATE_MISSING_DIRS, 1); curl_easy_setopt(curl, CURLOPT_DEBUGFUNCTION, debugFun); res = curl_easy_perform(curl); if(0 != res) { fclose(sendFile); fclose(debugFile); curl_easy_cleanup(curl); curl_global_cleanup(); return -1; } curl_easy_cleanup(curl); fclose(sendFile); fclose(debugFile); curl_global_cleanup(); return 0; }
使用示範:
#./ftp 192.168.31.145 user passwd /root/wanghf/curl destFile srcFile
下面是debugFile.txt中的信息:
About to connect() to 192.168.31.145 port 21
Trying 192.168.31.145... connected
Connected to 192.168.31.145 (192.168.31.145) port 21
Entry path is '/root'
Connect data stream passively
disabling EPSV usage
Trying 192.168.31.145... connected
Connecting to 192.168.31.145 (192.168.31.145) port 51581
Remembering we are in dir /root/wanghf/curl/
Connection #0 to host 192.168.31.145 left intact
Closing connection #0
剛剛開始學習libcurl庫,還有很多的細節不是很熟悉,這個示例很簡單,也沒有考慮到任何的異常,僅僅能夠實現功能,能將文件上傳到ftp服務器上,使用該例子,需要開啓ftp服務器。
文章來源於:http://www.iteye.com/topic/628630