Download file using libcurl in C / C ++

I am creating an application (on Windows using Dev-C ++) and I want it to download a file. I do this using libcurl (I 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 does not close the file after the download is complete. I would like someone to give an example on how to load a file, either in c or in C ++. Thanks in advance!

+49
c file curl libcurl download
Oct 28 '09 at 10:19
source share
2 answers

The example you are using is incorrect. See the easy_setopt man page. In the example, write_data uses its own FILE, * outfile, not the fp specified in CURLOPT_WRITEDATA. Therefore closing fp causes problems - it doesn't even open.

This is more or less what it should look like (no libcurl available here for testing)

#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; } 



Updated: as suggested by @rsethc types.h and easy.h no longer in current versions of cURL.

+179
Oct 28 '09 at 10:33
source share

Just for those who are interested in you, you can avoid writing a user-defined function by passing NULL as the last parameter (if you are not going to perform additional processing of the returned data).
In this case, the default internal function is used.

Image Details http://curl.haxx.se/libcurl/c/curl_easy_setopt.html#CURLOPTWRITEDATA

Example

 #include <stdio.h> #include <curl/curl.h> int main(void) { CURL *curl; FILE *fp; CURLcode res; char *url = "http://stackoverflow.com"; char outfilename[FILENAME_MAX] = "page.html"; curl = curl_easy_init(); if (curl) { fp = fopen(outfilename,"wb"); curl_easy_setopt(curl, CURLOPT_URL, url); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, NULL); curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp); res = curl_easy_perform(curl); curl_easy_cleanup(curl); fclose(fp); } return 0; } 
+14
Feb 05 '14 at 9:45
source share



All Articles