Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cURL - put output into variable?

Tags:

c

libcurl

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

like image 577
Mike Avatar asked Apr 05 '10 09:04

Mike


People also ask

How do I declare a variable in curl?

Declaring Local Variables and Constants The Curl language naming conventions for variables suggest using lowercase letters and a hyphen to join multiple words (for example, variable-name). is the data type of the variable. Specify any valid data type. type is required if value is not specified.

What is the output of curl command?

The syntax for the curl command is as follows: curl [options] [URL...] In its simplest form, when invoked without any option, curl displays the specified resource to the standard output. The command will print the source code of the example.com homepage in your terminal window.


1 Answers

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.

like image 69
YOU Avatar answered Sep 20 '22 13:09

YOU