在C / C使用libcurl的下载文件++ [英] Download file using libcurl in C/C++
问题描述
我建立一个应用程序(使用开发 - C ++窗口),我希望它下载文件。我做这个用的libcurl(我已经安装了源$ C $ c。使用帕克曼)。我发现了一个工作示例(<一个href=\"http://siddhantahuja.word$p$pss.com/2009/04/12/how-to-download-a-file-from-a-url-and-save-onto-local-directory-in-c-using-libcurl/\">http://siddhantahuja.word$p$pss.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使用自己的文件,* 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
不是present的建议当前版本的卷曲了。
Updated: as suggested by @rsethc types.h
and easy.h
aren't present in current cURL versions anymore.
这篇关于在C / C使用libcurl的下载文件++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!