• 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;
    };

     

  • 相关阅读:
    第七届蓝桥杯javaB组真题解析-煤球数目(第一题)
    考生须知
    2016年12月1日
    蓝桥网试题 java 基础练习 矩形面积交
    蓝桥网试题 java 基础练习 矩阵乘法
    蓝桥网试题 java 基础练习 分解质因数
    蓝桥网试题 java 基础练习 字符串对比
    个人银行账户管理程序
    new和delete的三种形式详解
    C++的六个函数
  • 原文地址:https://www.cnblogs.com/vc60er/p/3998122.html
Copyright © 2020-2023  润新知