使用curl下载文件

curl是一个非常好的网络传输库,使用也很简单。常用的使用方式是用它来下载资源文件,以下提供一个下载方法

 

 1 #include <stdio.h>
 2 #include <iostream.h>
 3 #include <curl/curl.h>
 4 
 5 using namespace std;
 6 
 7 int download(string url, string local_file, int down_speed)
 8 {
 9   CURL *image;
10   CURLcode imgresult;
11   FILE *fp;
12   //url_download.c_str();
13 
14     image = curl_easy_init();
15     if( image )
16      {
17         //Open File
18         fp = fopen(local_file.c_str(), "w");
19         if( fp == NULL ) cout << "File cannot be opened";
20         
21         curl_easy_setopt(image, CURLOPT_WRITEFUNCTION, NULL);
22         curl_easy_setopt(image, CURLOPT_WRITEDATA, fp);
23         curl_easy_setopt(image, CURLOPT_URL, url.c_str());
24         curl_easy_setopt(image, CURLOPT_FOLLOWLOCATION, 1);
25 //这里限速 100KB/s
26         curl_easy_setopt(image, CURLOPT_MAX_RECV_SPEED_LARGE, (curl_off_t)100 * 1024);
27         curl_easy_setopt(image, CURLOPT_NOPROGRESS, 0);
28         //CURLOPT_RESUME_FROM
29         
30         // Grab image
31         imgresult = curl_easy_perform(image);
32         if( imgresult )
33             {
34                 cout << "Cannot grab the File!\n";
35             }
36     }
37     //Clean up the resources
38     curl_easy_cleanup(image);
39     //Close the file
40     fclose(fp);
41     return 0;
42 }

 

 

 

posted @ 2013-11-01 15:29  haroel  阅读(4249)  评论(0编辑  收藏  举报