Better libcurl from C++

October 24, 2008

I’ve been a longtime fan of libcurl. But I’m a C++ author and so the c level of that is not where I want to be (and cURLpp looks ungainly for my minor usage).

Firing up google on “libcurl C++” yields “Using libcurl from C++ |” as the #1 entry. This article show a good starting example, but it’s not quite there. Here’s a cleaned up snippet:

Now that is a totally legitimate use and it works fine. But do you see the problem?
Yep, the data (buffer) is global, as is the writer but that isn’t as big a deal. This
is not good for many applications and is not good C++.

So let’s encapsulate that bad boy shall we? It’s really not all that hard, so here’s some example code.

Now that example has all kinds of missing things and the object is useless beyond one request but that is not the point, it’s a contrived example. The point is that your buffer is no longer global and it’s protected by your class. You can make multiple requests without having to grab the data off by yourself. That’s the big deal.

I don’t want this to seem like I am putting down LuckySpin. It’s a good example, I feel this is just a step better.

Categories: Geek
Tags: , ,


  1. theCloud says:

    Thanks dude ! I learn cpp for about one year.
    Yesterday, I was doing the same thing you did here. With some errors, now fixed :)
    Rhanks !

  2. John Hobbs says:

    You’re welcome!

  3. Keshav Bahadoor says:


    The curlWriter won’t always work for responses that are longer than expected; it does not handle these adequately.
    The following fix worked for us:

    static int curlWriter(char* data, size_t size, size_t nmemb, std::string *buffer)
    int result = 0;
    if (buffer != NULL ) {
    //buffer->assign(data, size * nmemb);
    *buffer += data; // Append instead
    result = size * nmemb;
    return result;

Leave A Comment

Your email will not be published.