curl最简单的下载功能的使用

下面是curl最简单的下载示例,其实再强大的功能库,helloworld程序也是很重要,让使用的人一眼就看出好用不好用~

这里包含了#include<string>会导致编译错误,需要把share.h重命名一下,再编译



#include "stdafx.h"
#include "curl/curl.h"
#include <string>

#include "curl/easy.h"

using namespace std;

static size_t downLoadPackage(void *ptr, size_t size, size_t nmemb, void *userdata)
{
	FILE *fp = (FILE*)userdata;
	size_t written = fwrite(ptr, size, nmemb, fp);
	return written;
}

int assetsManagerProgressFunc(void *ptr, double totalToDownload, double nowDownloaded, double totalToUpLoad, double nowUpLoaded)
{
	static int percent = 0;
	int tmp = 0;
	if ( totalToDownload > 0 )
	{
		tmp = (int)(nowDownloaded / totalToDownload * 100);
	}
	
	printf("下载进度%0d%%\r", tmp);
	return 0;
}

bool downLoad(void *_curl, std::string _packageUrl, std::string _storagePath, std::string fileName )
{
	// Create a file to save package.
	const string outFileName = _storagePath + fileName;
	FILE *fp = fopen(outFileName.c_str(), "wb");
	if (! fp)
	{
		return false;
	}

	// Download pacakge
	CURLcode res;
	curl_easy_setopt(_curl, CURLOPT_URL, _packageUrl.c_str());
	curl_easy_setopt(_curl, CURLOPT_WRITEFUNCTION, downLoadPackage);
	curl_easy_setopt(_curl, CURLOPT_WRITEDATA, fp);
	curl_easy_setopt(_curl, CURLOPT_NOPROGRESS, false);
	curl_easy_setopt(_curl, CURLOPT_PROGRESSFUNCTION, assetsManagerProgressFunc);
	//curl_easy_setopt(_curl, CURLOPT_PROGRESSDATA, this);
	curl_easy_setopt(_curl, CURLOPT_NOSIGNAL, 1L);
	curl_easy_setopt(_curl, CURLOPT_LOW_SPEED_LIMIT, 1L);
	curl_easy_setopt(_curl, CURLOPT_LOW_SPEED_TIME, 5L);

	res = curl_easy_perform(_curl);
	curl_easy_cleanup(_curl);
	if (res != 0)
	{
		fclose(fp);
		return false;
	}

	fclose(fp);
	return true;
}

int _tmain(int argc, _TCHAR* argv[])
{
	CURL* _curl = curl_easy_init();
	if (! _curl)
	{
		return 0;
	}

	downLoad(_curl, "http://ardownload.adobe.com/pub/adobe/reader/win/11.x/11.0.01/en_US/AdbeRdr11001_en_US.exe", "./", "AdbeRdr11001_en_US.exe");

	getchar();
	return 0;
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值