#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