Libcurl and its usage

Libcurl is a free and easy-to-use client-side URL transfer library. There are two interfaces available a synchronous and an asynchronous one… The synchronous easy interface is easy to use for file transfer operations.

A init function is used for some initializations. curl_easy_init() starts a libcurl easy session. This must be the first function to be called and this must have a corresponding call to the curl_easy_cleanup(). This returns a handle which is the input to the other interface functions used in libcurl or NULL on error.

curl_easy_cleanup() ends a libcurl easy session. This must be the last function to be called for an easy session. This kills the handle and all memory associated with it.

curl_easy_setopt() is a function to tell the libcurl how to behave.

curl_easy_setopt(CURL *handle, CURLoption option, parameter);
eg : To set an url – curl_easy_setopt(curl, CURLOPT_URL, url);
To write data to a file –
curl_easy_setopt(easyhandle,CURLOPT_WRITEDATA,f1);

curl_easy_perform() performs a file transfer.


#include curl/curl.h
#include stdio.h
#include stdlib.h

int main(int argc, char *argv[])
{
FILE * f1 = fopen(argv[1],"w");
CURL * easyhandle = curl_easy_init();
if(argc == 1){
perror("pass the required arguments, filename and url");
exit(1);
}
curl_easy_setopt(easyhandle,CURLOPT_URL,argv[2]);
curl_easy_setopt(easyhandle,CURLOPT_WRITEDATA,f1);
curl_easy_perform(easyhandle);
curl_easy_cleanup(easyhandle);
return 0;
}

Leave a comment