I got a function off of a friend that he found on the net. Problem is, neither of us understand how it works. It copies the contents of the webpage to the string.
We’re using cURL to connect to a php page.
The function in question is:
std::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.append((char *)ptr);
contents.append(1,lastchar);
*((char *) ptr + numbytes - 1) = lastchar; // Might not be necessary.
return size*nmemb;
}
Its called in this function:
curl_easy_setopt(curl,CURLOPT_WRITEFUNCTION,handle_data);
Any explanations into how this works would be great.
Cheers.
I think this is correct:
Having said all that, I’m not sure why the whole guts of handle_data() isn’t simply this:
…which I think would accomplish the exact same thing, only more correctly, since the published version will stop early if the buffer at ‘ptr’ contains an embedded null character. (Of course that’s probably not a use case for this function anyway.)