歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux編程 >> Linux編程

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;
}

Ubuntu 用戶安裝下載器 cURL 7.36.0  http://www.linuxidc.com/Linux/2014-05/102269.htm

Linux curl使用簡單介紹 http://www.linuxidc.com/Linux/2008-01/10891.htm

Unix下Curl的使用方法及常用功能記錄分享 http://www.linuxidc.com/Linux/2012-08/69154.htm

curl命令使用 http://www.linuxidc.com/Linux/2014-09/107018.htm

Copyright © Linux教程網 All Rights Reserved