C++ libcurl function


libcurl is a part of the cURL project and is a C library for accessing URLs on the web. I have included a basic program below, which accesses google, and returns the response as a string. cURL is great for building standalone download managers, however the function curl_httpget() below is not ideal for large downloads because it stores the complete file in memory (in a string object) before doing anything with it. The following program is just a basic demonstration of libcurl.

In linux, you will need to install the package curl-devel. This includes the header and library files, as well as the curl-config utility for compiling. Though it is better to use a makefile, it is possible to compile the following program in one line:
g++ `curl-config --libs` main.cpp -o curltest

main.cpp
#include <iostream>
#include <string>
#include <curl/curl.h>

using namespace std;
 
int writer(char *data, size_t size, size_t nmemb, string *buffer);
string curl_httpget(const string &url);
 
int main(int argc, char *argv[])
{
    cout << curl_httpget("http://www.google.com") << endl;
}
 
string curl_httpget(const string &url)
{
    string buffer;
 
    CURL *curl;
    CURLcode result;
 
    curl = curl_easy_init();
 
    if (curl)
    {
      curl_easy_setopt(curl, CURLOPT_URL, url.c_str()  );
      curl_easy_setopt(curl, CURLOPT_HEADER, 0);
      curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, writer);
      curl_easy_setopt(curl, CURLOPT_WRITEDATA, &buffer);
 
      result = curl_easy_perform(curl);//http get performed
 
      curl_easy_cleanup(curl);//must cleanup
 
      //error codes: http://curl.haxx.se/libcurl/c/libcurl-errors.html
      if (result == CURLE_OK)
          return buffer;
      //curl_easy_strerror was added in libcurl 7.12.0
      cerr << "error: " << result << " " << curl_easy_strerror(result) <<endl;
      return "";
    }
 
    cerr << "error: could not initalize curl" << endl;
    return "";
}
 
int writer(char *data, size_t size, size_t nmemb, string *buffer)
{
  int result = 0;
  if (buffer != NULL)
  {
      buffer->append(data, size * nmemb);
      result = size * nmemb;
  }
  return result;
}


In this case there is no query string in the url (the ?a=b of index.php?a=b). However it is highly recommended that you use a function like urlencode() to sanitize the values in the query string. For the reason why, read the article on urlencode().