使用curl下載文件

curl是一個很是好的網絡傳輸庫,使用也很簡單。經常使用的使用方式是用它來下載資源文件,如下提供一個下載方法ios

 

 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 }
相關文章
相關標籤/搜索