Skip to content

Instantly share code, notes, and snippets.

@alghanmi
Created May 5, 2014 20:12
Show Gist options
  • Save alghanmi/c5d7b761b2c9ab199157 to your computer and use it in GitHub Desktop.
Save alghanmi/c5d7b761b2c9ab199157 to your computer and use it in GitHub Desktop.
cURL C++ Example
#include <iostream>
#include <string>
#include <curl/curl.h>
static size_t WriteCallback(void *contents, size_t size, size_t nmemb, void *userp)
{
((std::string*)userp)->append((char*)contents, size * nmemb);
return size * nmemb;
}
int main(void)
{
CURL *curl;
CURLcode res;
std::string readBuffer;
curl = curl_easy_init();
if(curl) {
curl_easy_setopt(curl, CURLOPT_URL, "http://www.google.com");
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &readBuffer);
res = curl_easy_perform(curl);
curl_easy_cleanup(curl);
std::cout << readBuffer << std::endl;
}
return 0;
}
@voiduin
Copy link

voiduin commented Jul 21, 2024

@alghanmi Hi!

First off, thank you for sharing your code example! It was incredibly helpful for getting me started quickly. However, I wanted to point out a couple of discrepancies that I noticed:

  1. Missing global initialization:
    The libcurl documentation recommends using curl_global_init() at the beginning of the program to set up the necessary environment for curl operations. See "Global preparation" section:
    - https://curl.se/libcurl/c/libcurl-tutorial.html
  2. Callback prototype mismatch:
    The prototype for the callback function seems to be inconsistent with the one documented on the official libcurl site. The prototype for this callback function is described here:
    - https://curl.se/libcurl/c/CURLOPT_WRITEFUNCTION.html
size_t write_callback(char *ptr, size_t size, size_t nmemb, void *userdata);

On a related note, I've created a more detailed setup documentation and added a simple example as well as a slightly more complex one that includes POST requests, which some may find useful.
- https://github.com/null-galaxy/cpp-curl-example

Thanks again for your contribution—it was a great starting point for me!

Best regards,
@voiduin

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment