libcurl实现的FTPClient

本文介绍了一种使用C++结合libcurl库实现FTP文件上传的方法。通过定义FTPClient类,实现了文件上传功能,并提供了进度回调机制。代码示例展示了如何配置libcurl进行FTP上传,包括设置URL、读取本地文件、指定文件大小及进度回调函数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值