使用cURL下载文件的简单方法

时间:2013-02-20 17:17:23

标签: c++ macos curl download

在我的程序中,我想下载一些文件。所以我使用了cURL并使用了这段代码(从这里Download file using libcurl in C/C++采取和修改了一点):

#include "curl.h"
using namespace std;

size_t write_data(void *ptr, size_t size, size_t nmemb, FILE *stream) {
    size_t written;
    written = fwrite(ptr, size, nmemb, stream);
    return written;
}

int DlZip(){
    CURL *curl;
    FILE *fp;
    CURLcode res;
    string url = "http://wordpress.org/extend/plugins/about/readme.txt";
    char outfilename[FILENAME_MAX] = "/Users/Me/Desktop/bbb.txt";
    curl = curl_easy_init();
    if (curl) {
        fp = fopen(outfilename,"wb");
        curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data);
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp);
        res = curl_easy_perform(curl);
        curl_easy_cleanup(curl);
        fclose(fp);
    }
    return 0;
}

但没有任何反应,我的桌面上没有任何文件: - /

我的代码有什么问题? 或者如果你有一个简单的功能可以使用,你能给我吗?

谢谢!

1 个答案:

答案 0 :(得分:0)

检查以下代码

#include <cstdio>
#include <curl/curl.h>
#include <curl/types.h>
#include <curl/easy.h>
#include <string>



using namespace std;

size_t write_data(void *ptr, size_t size, size_t nmemb, FILE *stream) {
    size_t written;
    written = fwrite(ptr, size, nmemb, stream);
    return written;
}

int main(){
    CURL *curl;
    FILE *fp;
    CURLcode res;
    string url = "http://www.joes-hardware.com/tools.html";
    char outfilename[FILENAME_MAX] = "./MyText.txt";
    curl = curl_easy_init();
    if (curl) {
        fp = fopen(outfilename,"wb");
        curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data);
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp);
        res = curl_easy_perform(curl);
        curl_easy_cleanup(curl);
        fclose(fp);
    }
    return 0;
}

工作正常。 问题是 - 此代码无法使用https,因此当您在浏览器中打开并通过上述代码提供的url时,会产生单独的响应。