libcurl使用HTTP的get请求来下载文件

首先设置好下载链接

int ret = curl_easy_setopt(easy_handle, CURLOPT_URL, "http://speedtest.wdc01.softlayer.com/downloads/test10.zip");

然后设置CURLOPT_WRITEFUNCTION属性保存接受的数据

ret |= curl_easy_setopt(easy_handle, CURLOPT_WRITEFUNCTION, write_callback);
write_callback是用户自定义的回调函数,用来保存接受到的数据,其原型为
size_t write_callback(char *ptr, size_t size, size_t nmemb, void *userdata);

此函数返回实际接受到的字节数,如果返回的字节数与发送的不一致会导致中断传输。其中ptr表示接受的数据,size表示单块数据的大小,nmemb表示有几块数据,size*nmemb表示数据的大小,userdata表示用户自定义的参数,通过设置CURLOPT_WRITEDATA属性来传递,可以将其设置为文件指针,这样就可以保存接受到的数据了,如果是写C++,此函数应声明为static函数

Your callback should return the number of bytes actually taken care of. If that amount differs from the amount passed to your callback function, it'll signal an error condition to the library. This will cause the transfer to get aborted and the libcurl function used will return CURLE_WRITE_ERROR.

FILE *fp;
fopen_s(&fp, "test10.zip", "ab+"); // windows下的,linux平台用fopen
ret |= curl_easy_setopt(easy_handle, CURLOPT_WRITEDATA, fp); // fp当作参数传递给write_callback函数


write_callback的实现

size_t write_callback(char *ptr, size_t size, size_t nmemb, void *userdata)
{
	FILE *fp = static_cast<FILE *>(userdata);
	size_t length = fwrite(ptr, size, nmemb, fp);
	if (length != nmemb)
	{
		return length;
	}

	return size * nmemb;
}

整个工程的GitHub地址:https://github.com/forzxy/HttpClient



  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值