开发者

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;
}


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.


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜