cURL provides two kinds of interface to access the internet: easy and multi. Easy interface is synchronous and efficient. The multi interface has asynchronous method also multi-file data transfer ability.
In this tutorial, we are going to demonstrate how to simply download an HTTP file from internet with cURL easy method in C++.
Easy interface
Let’s talk about the easy interface, steps for data transfer purpose can be separated into three.
curl_easy_init()
Initialization an easy-session and get a handle. The handle will be used as an input for the following functions.
curl_easy_setopt()
Setting all the options you want for the internet data transfer including URL, port or the way to write data.
curl_easy_perform()
After the options you want for the upcoming transfer has been settled. you can call the curl_easy_perform() function. It will do the entire job and won’t return until the job has been done or failed.
curl_easy_cleanup()
After the job has been done, the curl_easy_leanup()
method will clean up the easy-session handle for you.
Here is a short demonstration of file downloading from http://www.example.com. We are going to save it to example.html in your local folder.
#include <stdio.h>
#include <curl/curl.h>
int main(void)
{
CURL *curl;
FILE *fp;
CURLcode res;
char *url = "http://www.example.com";
char outfilename[FILENAME] = "example.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;
}
Options of curl_easy_setopt()
are listed below:
Network Options | Function |
---|---|
CURLOPT_URL | URL to work on |
CURLOPT_WRITEFUNCTION | Callback for writing data |
CURLOPT_WRITEDATA | Data pointer to pass to the write callback |
Successful run will give you the ability to download the html file you want like this :-D
keywords: cURL, C++, Code::Block
Comments
Post a Comment