int download_file(const char* url, const char *outfilename){
CURL *curl;
FILE *fp;
CURLcode res;
/* 调用curl_global_init()初始化libcurl */
res = curl_global_init(CURL_GLOBAL_ALL);
if (CURLE_OK != res)
{
printf("init libcurl failed.");
curl_global_cleanup();
return -1;
}
/* 调用curl_easy_init()函数得到 easy interface型指针 */
curl = curl_easy_init();
if (curl) {
fp = fopen(outfilename,"wb");
/* 调用curl_easy_setopt()设置传输选项 */
res = curl_easy_setopt(curl, CURLOPT_URL, url);
if (res != CURLE_OK)
{
fclose(fp);
curl_easy_cleanup(curl);
return -1;
}
/* 根据curl_easy_setopt()设置的传输选项,实现回调函数以完成用户特定任务 */
res = curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, CommonTools::writedata2file);
if (res != CURLE_OK){
fclose(fp);
curl_easy_cleanup(curl);
return -1;
}
/* 根据curl_easy_setopt()设置的传输选项,实现回调函数以完成用户特定任务 */
res = curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp);
if (res != CURLE_OK)
{
fclose(fp);
curl_easy_cleanup(curl);
return -1;
}
res = curl_easy_perform(curl);
// 调用curl_easy_perform()函数完成传输任务
fclose(fp);
/* Check for errors */
if(res != CURLE_OK){
fprintf(stderr, "curl_easy_perform() failed: %s\n",curl_easy_strerror(res));
curl_easy_cleanup(curl);
return -1;
}
/* always cleanup */
curl_easy_cleanup(curl);
// 调用curl_easy_cleanup()释放内存
}
curl_global_cleanup();
return 0;
}