libcurl下载文件

一、初始化

CURL *pHandler = curl_easy_init();

 

二、设置请求参数;

调用curl_easy_setopt方法,设置选项

curl_easy_setopt(pHandler , CURLOPT_WRITEFUNCTION, WriteData);

curl_easy_setopt(pHandler , CURLOPT_WRITEDATA, pFile);

 

//设置请求的url地址

curl_easy_setopt(pHandler , CURLOPT_URL, strUrl.c_str());

//如果为post请求,这里设置提交的参数

//curl_easy_setopt(pHandler , CURLOPT_POSTFIELDS, strPostData.c_str());

curl_easy_setopt(pHandler , CURLOPT_FAILONERROR, true);
curl_easy_setopt(pHandler , CURLOPT_TIMEOUT, 60);  //超时时间(秒)
curl_easy_setopt(pHandler , CURLOPT_NOSIGNAL, true);

 

三、执行下载

CURLcode codeRet = curl_easy_perform(pHandler);

 

四、获取返回的http状态码

long retcode = 0;

curl_easy_getinfo(pHandler, CURLINFO_RESPONSE_CODE , &retcode);

 

五、清理

curl_easy_cleanup(pHandler);

 

if (codeRet == CURLE_OK && (retcode == 200 || retcode == 304 || retcode == 204))

{

//下载成功

}

else

{

//下载失败

}

 

size_t WriteData(const char *ptr, size_t size, size_t nmemb, FILE *stream)
{
    if (!ptr || !stream)
    {
        return 0;
    }


    return fwrite(ptr, size, nmemb, stream);
}

 

关于文件的读写操作,可以参考这里:

fopen

fseek

ftell

fread

fwrite

原文地址:https://www.cnblogs.com/meteoric_cry/p/3681546.html