1

在我的程序中,我想下载一些文件。所以我使用了 cURL 并使用了这段代码(从这里下载并修改了一点使用 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;
}

但是什么也没发生,我的桌面上也没有任何文件:-/

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

谢谢!

4

1 回答 1

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您在浏览器中打开并通过上述代码提供时 - 会产生单独的响应。

于 2014-08-28T05:13:59.367 回答