c - 在 C/C++ 中使用 libcurl 下载文件

标签 c file download libcurl

我正在构建一个应用程序(在使用 Dev-C++ 的 Windows 上),我希望它下载一个文件。我正在使用 libcurl 执行此操作(我已经使用 packman 安装了源代码)。我找到了一个工作示例 ( http://siddhantahuja.wordpress.com/2009/04/12/how-to-download-a-file-from-a-url-and-save-onto-local-directory-in-c-using-libcurl/ ),但它不会在下载完成后关闭文件。我想要一个如何用 C 语言下载文件的示例。

最佳答案

您使用的示例是错误的。请参阅 easy_setopt 的手册页.在示例中,write_data 使用它自己的 FILE,*outfile,而不是在 CURLOPT_WRITEDATA 中指定的 fp。这就是为什么关闭 fp 会导致问题 - 它甚至没有打开。

这或多或少应该是这样的(这里没有可供测试的 libcurl)

#include <stdio.h>
#include <curl/curl.h>
/* For older cURL versions you will also need 
#include <curl/types.h>
#include <curl/easy.h>
*/
#include <string>

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

int main(void) {
    CURL *curl;
    FILE *fp;
    CURLcode res;
    char *url = "http://localhost/aaa.txt";
    char outfilename[FILENAME_MAX] = "C:\\bbb.txt";
    curl = curl_easy_init();
    if (curl) {
        fp = fopen(outfilename,"wb");
        curl_easy_setopt(curl, CURLOPT_URL, url);
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data);
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp);
        res = curl_easy_perform(curl);
        /* always cleanup */
        curl_easy_cleanup(curl);
        fclose(fp);
    }
    return 0;
}

更新:根据@rsethc 的建议,types.heasy.h 不再出现在当前的 cURL 版本中。

关于c - 在 C/C++ 中使用 libcurl 下载文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1636333/

相关文章:

c - 查找数组的平均值

c - 可以覆盖声明的 : char * a = "abc";?

c -/proc/pid/stat 中文件名的奇怪行为

python - 为什么这个 python 代码会在不更改文件的情况下将我的文件大小加倍?

Java 打开并读取目录中的文件

javascript - 如何使用javascript onload 下载多个图像?

c - 在c中链接2个目标文件以创建可执行文件

file - 遍历文件夹并检查是否存在某个文件

delphi - 在 Delphi 的线程中从互联网下载文件

ios - Phonegap/Cordova取消文件传输下载