首页 > 代码库 > 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下载文件