首页 > 代码库 > c/c++常用代码--使用libcurl下载文件
c/c++常用代码--使用libcurl下载文件
#pragma once#include <stdio.h>#include <stdlib.h>#include <curl/curl.h>#ifdef _DEBUG#pragma comment(lib, "libcurld_imp.lib")#else#pragma comment(lib, "libcurl_imp.lib")#endifclass CUrlInit{public: CUrlInit() { curl_global_init(CURL_GLOBAL_ALL); } ~CUrlInit() { curl_global_cleanup(); } protected: static CUrlInit m_Initialize;};CUrlInit CUrlInit::m_Initialize;class CMyUrl{public: CMyUrl() { /* init the curl session */ curl_handle = curl_easy_init(); } ~CMyUrl() { /* cleanup curl stuff */ curl_easy_cleanup(curl_handle); } public: int get_file(const char* szUrl, const char* szFile) { /* set URL to get */ curl_easy_setopt(curl_handle, CURLOPT_URL, szUrl); /* no progress meter please */ curl_easy_setopt(curl_handle, CURLOPT_NOPROGRESS, 1L); /* send all data to this function */ curl_easy_setopt(curl_handle, CURLOPT_WRITEFUNCTION, write_data); /* open the files */ FILE* bodyfile = fopen(szFile, "wb"); if (bodyfile == NULL) { curl_easy_cleanup(curl_handle); return -1; } /* we want the body be written to this file handle instead of stdout */ curl_easy_setopt(curl_handle, CURLOPT_WRITEDATA, bodyfile); /* get it! */ curl_easy_perform(curl_handle); /* close the body file */ fclose(bodyfile); return 0; }protected: static size_t write_data(void *ptr, size_t size, size_t nmemb, void *stream) { int written = fwrite(ptr, size, nmemb, (FILE *)stream); return written; }protected: CURL *curl_handle;};
c/c++常用代码--使用libcurl下载文件
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。