zoukankan      html  css  js  c++  java
  • 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")
    #endif


    class 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)
        {
            curl_easy_reset(m_curl);
            
            /* 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;
    };

     

  • 相关阅读:
    第二十一章 PHP编译安装(centos7)
    第二十章 nginx常见问题
    第十九章 keepalived高可用
    dijkstra
    求逆序对
    A
    P2014 [CTSC1997]选课
    樱花 混合背包
    1401D
    CF1343D
  • 原文地址:https://www.cnblogs.com/vc60er/p/3998122.html
Copyright © 2011-2022 走看看