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

     

  • 相关阅读:
    本月周六周日LIST集合
    c#动态调用WEBSERVICE接口
    c#调用
    web上传下载文件
    MVC 的知识
    MongoDB 无法创建抽象类的问题,
    并行活动
    C# 字符串计算表达式
    c# 将字符串转换为逻辑表达式(字符串转换布尔)
    C# 中间语言、CLR、CTS、CLS
  • 原文地址:https://www.cnblogs.com/vc60er/p/3998122.html
Copyright © 2011-2022 走看看