libcurl库的使用(通过libcurl库下载url图像)
1.??????從http://curl.haxx.se/download.html下載libcurl源碼,解壓縮;
2.??????通過CMake(cmake-gui)生成vs2013 x64位 CURL.sln;
3.??????打開CURL.sln,編譯會(huì)生成libcurl.dll動(dòng)態(tài)庫(kù);
4.??????在CURL.sln基礎(chǔ)上,添加一個(gè)testlibcurl控制臺(tái)工程;
5.??????testlibcurl.cpp:
?
#include "stdafx.h"
#include <iostream>
#include <curl/curl.h>size_t callbackfunction(void *ptr, size_t size, size_t nmemb, void* userdata)
{FILE* stream = (FILE*)userdata;if (!stream) {printf("!!! No stream\n");return 0;}size_t written = fwrite((FILE*)ptr, size, nmemb, stream);return written;
}bool download_jpeg(char* url)
{FILE* fp = fopen("out.jpg", "wb");if (!fp) {printf("!!! Failed to create file on the disk\n");return false;}CURL* curlCtx = curl_easy_init();curl_easy_setopt(curlCtx, CURLOPT_URL, url);curl_easy_setopt(curlCtx, CURLOPT_WRITEDATA, fp);curl_easy_setopt(curlCtx, CURLOPT_WRITEFUNCTION, callbackfunction);curl_easy_setopt(curlCtx, CURLOPT_FOLLOWLOCATION, 1);CURLcode rc = curl_easy_perform(curlCtx);if (rc) {printf("!!! Failed to download: %s\n", url);return false;}long res_code = 0;curl_easy_getinfo(curlCtx, CURLINFO_RESPONSE_CODE, &res_code);if (!((res_code == 200 || res_code == 201) && rc != CURLE_ABORTED_BY_CALLBACK)) {printf("!!! Response code: %d\n", res_code);return false;}curl_easy_cleanup(curlCtx);fclose(fp);return true;
}size_t write_data(void *ptr, size_t size, size_t nmemb, FILE *stream)
{size_t written = fwrite(ptr, size, nmemb, stream);return written;
}bool download_jpeg2(char* url)
{CURL *curl;FILE *fp;CURLcode res;char* outfilename = "out2.jpg";curl = curl_easy_init();if (curl) {fp = fopen(outfilename, "wb");curl_easy_setopt(curl, CURLOPT_URL, url);curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data);curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp);res = curl_easy_perform(curl);/* always cleanup */curl_easy_cleanup(curl);fclose(fp);}else {printf("!!!curl init failed\n");return false;}return true;
}int main(int argc, char* argv[])
{char* url = "http://f.hiphotos.baidu.com/image/pic/item/d043ad4bd11373f0671f5d95a60f4bfbfbed0493.jpg";#if 1if (!download_jpeg(url)) {printf("!! Failed to download file: %s\n", url);return -1;}
#elseif (!download_jpeg2(url)) {printf("!! Failed to download file: %s\n", url);return -1;}
#endifstd::cout << "ok!" << std::endl;return 0;
}
參考文獻(xiàn):
?
?
1.??????http://stackoverflow.com/questions/10112959/download-an-image-from-server-curl-however-taking-suggestions-c
2.??????http://stackoverflow.com/questions/1636333/download-file-using-libcurl-in-c-c
3.??????https://www.hackthissite.org/articles/read/1078
4.??????http://curl.askapache.com/c/example.html
?
GitHub:https://github.com/fengbingchun/Libcurl_Test
總結(jié)
以上是生活随笔為你收集整理的libcurl库的使用(通过libcurl库下载url图像)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Ubuntu中Atom编辑器显示中文乱码
- 下一篇: Linux下多线程编程互斥锁和条件变量的