在 C/C++ 中使用 libcurl 下载文件 [英] Download file using libcurl in C/C++
问题描述
我正在构建一个应用程序(在 Windows 上使用 Dev-C++)并且我希望它下载一个文件.我正在使用 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 或 c++ 下载文件.提前致谢!
I am building an application (on windows using Dev-C++) and I want it to download a file. I am doing this using libcurl (I have already installed the source code using packman). I found a working example (http://siddhantahuja.wordpress.com/2009/04/12/how-to-download-a-file-from-a-url-and-save-onto-local-directory-in-c-using-libcurl/) but it doesn't close the file after download is complete. I would like someone to give an example on how to download a file, either in c or c++. Thanks in advance!
推荐答案
您使用的示例是错误的.请参阅 easy_setopt 的手册页.在示例中 write_data 使用它自己的 FILE,*outfile,而不是在 CURLOPT_WRITEDATA 中指定的 fp.这就是关闭 fp 会导致问题的原因 - 它甚至没有打开.
The example you are using is wrong. See the man page for easy_setopt. In the example write_data uses its own FILE, *outfile, and not the fp that was specified in CURLOPT_WRITEDATA. That's why closing fp causes problems - it's not even opened.
这或多或少应该是这样的(这里没有可测试的 libcurl)
This is more or less what it should look like (no libcurl available here to test)
#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 版本中.
Updated: as suggested by @rsethc types.h
and easy.h
aren't present in current cURL versions anymore.
这篇关于在 C/C++ 中使用 libcurl 下载文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!