Prasanth Madhavan
Prasanth Madhavan

Reputation: 13309

save the output of a curl perform to a vector<string> in c++

as my title says, i would like to save the output of a curl perform to a vector.. can any1 please give me a sample code? i was able to save it into a structure in c. but i want to save it to a vector that too in c++ and i'm a little unconfortable with c++.

    vector<string> contents;

size_t handle_data(void *ptr, size_t size, size_t nmemb, void *stream)
{
int numbytes = size*nmemb;
char lastchar = *((char *) ptr + numbytes - 1);
*((char *) ptr + numbytes - 1) = '\0';
contents.push_back((char *)ptr);
*((char *) ptr + numbytes - 1) = lastchar;  // Might not be necessary.
return size*nmemb;
}



int main(int argc, char *argv[])
{

vector<string>::iterator i;

CURL* curl = curl_easy_init();
if(curl)
    {
    curl_easy_setopt(curl,CURLOPT_URL, argv[1]);
    curl_easy_setopt(curl,CURLOPT_WRITEFUNCTION,handle_data);
    CURLcode res = curl_easy_perform(curl);
    curl_easy_cleanup(curl);
    if (res == 0){
        for(i=contents.begin();i!=contents.end();i++)
            cout << *i << endl;
    }else
        cerr << "Error: " << res << endl;
    }
return 0;
}

Upvotes: 2

Views: 2019

Answers (3)

redeye
redeye

Reputation: 123

Here's what you're probably looking for:

size_t handle_data(void *ptr, size_t size, size_t nmemb, void *stream)
 {
     size_t numbytes = size*nmemb;

     string temp(static_cast<char*>(ptr), nmemb);

     contents.push_back(temp);

     return numbytes;
 }

I'm fairly sure you don't want to write to the void *ptr you're passed by the CURL library. And it also looks like you are overwriting the last char of the memory address with '\0', then putting the original value back in there after pushing to the vector. I'm not sure this will work as expected.

Upvotes: 1

chris
chris

Reputation: 4026

Try cURLpp. Here's an example that might be useful.

Upvotes: 1

Ferruccio
Ferruccio

Reputation: 100668

I don't know curl, so I'm going to assume the setup code is correct. So what you want is the callback function to add a string for each block of data received to a vector of strings. This also assumes that the data coming back is 8-bit characters.

vector<string> contents;

size_t handle_data(void *ptr, size_t size, size_t nmemb, void *stream)
{
    contents.push_back(string(static_cast<const char*>(ptr), size * nmemb));
    return size * nmemb;
}

the "call" to string() actually constructs a string object initialized with a pointer and data length.

Upvotes: 2

Related Questions