我正在构建一个应用程序(在使用 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.h
和easy.h
不再出现在当前的 cURL 版本中。
关于c - 在 C/C++ 中使用 libcurl 下载文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1636333/