Linux编译安装libcurl并使用它编写ftp上传的C程序

下载curl-7.70.0.zip并解压
在curl-7.70.0的上一级目录编写一个curl_build.sh的文件,内容为:

cd curl-7.70.0
./configure --prefix=/curl/ --disable-shared --enable-static --without-libidn --without-ssl --without-librtmp --without-gnutls --without-nss --without-libssh2 --without-zlib --without-winidn --disable-rtsp --disable-ldap --disable-ldaps --disable-ipv6
make && make install

管理员权限下执行这个sh文件,这里我把它编译为静态库了,没有生成动态库,是为了简化。之后即可将/curl这个目录拷贝出去作为libcurl的sdk包了。

然后编写测试程序main.cpp:

#include <iostream>
#include <stdio.h>
#include <curl/curl.h>
#include <libgen.h>
using namespace std;

int g_log_count=0;

size_t read_data_callback(void* buffer, size_t size, size_t count, void* fp)
{
	int items=fread(buffer, size, count, (FILE*)fp);
	printf("第%d次传输了%d字节\n",++g_log_count,items*size);
	return items;
}

int main(int argc, char* argv[])
{
	if(argc<2)
	{
		printf("参数太少\n");
		return -1;
	}

	// 初始化libcurl
	CURLcode code;
	code = curl_global_init(CURL_GLOBAL_ALL);
	if (code != CURLE_OK)
	{
		cerr << "init libcurl failed." << endl;
		return -1;
	}
	
	FILE *fp = fopen(argv[1], "rb");
	if (NULL == fp)
	{
		cout << "can't open file." << endl;
		curl_global_cleanup();
		return -1;
	}

	// 获取文件大小
	fseek(fp, 0, 2);
	int file_size = ftell(fp);
	rewind(fp);

	// 获取easy handle
	CURL *easy_handle = NULL;
	easy_handle = curl_easy_init();
	if (NULL == easy_handle)
	{
		cerr << "get a easy handle failed." << endl;
		fclose(fp);
		curl_global_cleanup();
		return -1;
	}

	// 设置eash handle属性
	char url[256]={0};
	sprintf(url,"ftp://username:passwd@localhost/ftptest/%s",basename(argv[1]));
	curl_easy_setopt(easy_handle, CURLOPT_URL, url);
	curl_easy_setopt(easy_handle, CURLOPT_UPLOAD, 1L);
	curl_easy_setopt(easy_handle, CURLOPT_READFUNCTION, read_data_callback);
	curl_easy_setopt(easy_handle, CURLOPT_READDATA, fp);
	curl_easy_setopt(easy_handle, CURLOPT_INFILESIZE_LARGE, file_size);//最后一个参数是文件大小,类型为64位的整数
	
	// 执行上传操作
	code = curl_easy_perform(easy_handle);
	if (code == CURLE_OK)
		cout << "upload successfully." << endl;
	else
		cout<<"上传失败"<<endl;

	// 释放资源
	fclose(fp);
	curl_easy_cleanup(easy_handle);
	curl_global_cleanup();

	return 0;
}

makefile文件为:

main:main.cpp
	g++ main.cpp -I /curl/include -L /curl/lib -l curl -lpthread -fPIC -o main
clean:
	rm main

最后,切记关闭本机的防火墙,否则将会上传文件失败!!!
超级用户权限下执行如下命令以关闭防火墙:
#systemctl stop firewalld.service
然后即可运行测试程序,比如:
$./main testfile

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值