How to download a file from a URL and save onto local directory in C++ using libcurl

12 04 2009

#include <stdio.h>
#include <curl/curl.h>
#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;
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;
}
About these ads

Actions

Information

4 responses

26 10 2009
Marios

And then how can I close the file (“outfile”) after the download is completed?

26 10 2009
siddahuja

Try using fclose (outfile);

27 10 2009
Marios

Yes I tried that already a million of times. If I put that after curl_easy_cleanup(curl); it tells me that the var is not declared. If I put it after fprintf(stderr,”The body is \n”,outfilename); the file is closed and cannot be written.

26 10 2009
Marios

Yes I tried that already a million of times. If I put that after curl_easy_cleanup(curl); it tells me that the var is not declared. If I put it after fprintf(stderr,”The body is \n”,outfilename); the file is closed and cannot be written.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s




Follow

Get every new post delivered to your Inbox.

Join 79 other followers

%d bloggers like this: