FTPClient.h
#ifndef FTPClient_H
#define FTPClient_H
#if defined(_MSC_VER) || defined(_WIN32)
#define _CRT_SECURE_NO_WARNINGS
#pragma comment(lib,"libcurld.lib")
#endif
#include <stdio.h>
#include <curl.h>
typedef int(*pfunc_progress_callback)(void *p,
curl_off_t dltotal,
curl_off_t dlnow,
curl_off_t ultotal,
curl_off_t ulnow);
class FTPClient
{
public:
FTPClient();
~FTPClient();
int upload(const char* ip, const char* username, const char* passwd,
const char* localpath, const char* remotepath, pfunc_progress_callback pfunc);
};
#endif
FTPClient.cpp
#include "FTPClient.h"
FTPClient::FTPClient()
{
curl_global_init(CURL_GLOBAL_ALL);
}
FTPClient::~FTPClient()
{
curl_global_cleanup();
}
int FTPClient::upload(const char* ip,const char* username,const char* passwd,
const char* localpath, const char* remotepath, pfunc_progress_callback pfunc)
{
FILE* fp = fopen(localpath,"rb");
#ifdef __GNUC__
unsigned long long file_size;
struct stat statbuff;
stat(localpath, &statbuff);
file_size = statbuff.st_size;
#elif defined(_MSC_VER) || defined(_WIN32)
fseek(fp, 0, SEEK_END);
__int64 file_size = _ftelli64(fp);
rewind(fp);
#endif
CURL *easy_handle = curl_easy_init();//不能在多線程中共享這個句柄
char url[MAX_PATH];
sprintf(url, "ftp://%s:%s@%s/%s", username, passwd, ip, remotepath);
curl_easy_setopt(easy_handle, CURLOPT_UPLOAD, 1L);
curl_easy_setopt(easy_handle, CURLOPT_URL, url);
curl_easy_setopt(easy_handle, CURLOPT_READDATA, fp);
curl_easy_setopt(easy_handle, CURLOPT_INFILESIZE_LARGE, file_size);
if (pfunc)
{
curl_easy_setopt(easy_handle, CURLOPT_NOPROGRESS, 0);
//curl_easy_setopt(easy_handle, CURLOPT_XFERINFODATA, &someData);//可以爲下面的回調函數設置參數
curl_easy_setopt(easy_handle, CURLOPT_XFERINFOFUNCTION, pfunc);
}
CURLcode ret;
ret = curl_easy_perform(easy_handle);
fclose(fp);
return ret;
}
測試代碼main.cpp:
#include <stdio.h>
#include "FTPClient.h"
int progressCallback(void *p,
curl_off_t dltotal,
curl_off_t dlnow,
curl_off_t ultotal,
curl_off_t ulnow)
{
printf("已上傳:%%%g\n", ((double)ulnow / ultotal) * 100);
return 0;
}
int main()
{
FTPClient ftp;
char* localpath = "F:\\song\\軟件備份\\cn_windows_10_business_editions_version_1903_updated_july_2019_x64_dvd_68b4eeaa.iso";
char* remotepath = "ftpinput/cn_windows_10_business_editions_version_1903_updated_july_2019_x64_dvd_68b4eeaa.iso";
int ret = ftp.upload("222.18.149.196","user1","user1", localpath, remotepath, progressCallback);
if (ret == 0)
printf("上傳成功\n");
else
printf("上傳失敗,錯誤碼:%d\n", ret);
getchar();
return 0;
}