cURL - put output into variable?

Mike picture Mike · Apr 5, 2010 · Viewed 11.3k times · Source

I'm currently using this C code:

CURL *curl;
CURLcode res;

curl = curl_easy_init();
if (curl) {
    curl_easy_setopt(curl, CURLOPT_URL, "http://my-domain.org/");
    res = curl_easy_perform(curl);

    curl_easy_cleanup(curl);
}

It prints the output on the console. How can I get the same output, but read it into, say, a string? (This is a probably a basic question, but I do not yet understand the libcurl API...)

Thanks for any help!

Mike

Answer

YOU picture YOU · Apr 5, 2010

You need to pass a function and buffer to write it to buffer.

/* setting a callback function to return the data */
curl_easy_setopt(curl_handle, CURLOPT_WRITEFUNCTION, write_callback_func);

/* passing the pointer to the response as the callback parameter */
curl_easy_setopt(curl_handle, CURLOPT_WRITEDATA, &response);


/* the function to invoke as the data recieved */
size_t static write_callback_func(void *buffer,
                        size_t size,
                        size_t nmemb,
                        void *userp)
{
    char **response_ptr =  (char**)userp;

    /* assuming the response is a string */
    *response_ptr = strndup(buffer, (size_t)(size *nmemb));

}

Please take a look more info here.