0

I am sending the data from a file using the Libcurl post callback. The example here shows, how to send data as 1 byte per call from callback function. I have changed the code so the file is read into chunks. That pretty much works fine.

the current sample code is:

if(sizeleft){
 *( char *)ptr = readptr[0]; 
   readptr++;
   sizeleft--;
  return 1;
}

This example sends the data as 1 byte. but suppose i have to send it multiple bytes.I have tried to increment readptr by two each time and decreasing sizeleft by two and i return 2bytes at a time.

It didnt work like this and the data is corrupted.

I would appreciate if someone out there could help me out. Thank you

1 Answer 1

2

It's difficult to tell from your question exactly what you're doing, exactly what you'd expect to happen and exactly what actually happens. However it looks like you're on the right track.

The documentation for CURLOPT_READFUNCTION states that size * nitems (a.k.a. size * nmemb in the example) is the upper limit of the number of bytes you may write into buffer, and the return value of your function is the actual number of bytes that you wrote. Returning zero means that you have written everything you wish to write, and your callback function won't be called any more.

If the value you return from your function does not equal the number of bytes that you actually wrote into the buffer, then you can expect corruption.

PS: Something like:

// copy as many bytes as we can, up to either:
// * The number of bytes we have remaining.
//   or
// * The space available in ptr.
size_t maxBytes = size * nmemb;
size_t numBytes = std::min (maxBytes, sizeleft);
memcpy (ptr, readptr, numBytes);
readptr += numBytes;
sizeleft -= numBytes;
return numBytes;
Sign up to request clarification or add additional context in comments.

2 Comments

i have a confusion about std::max (maxBytes, sizeleft) . std::max would return the maximum of maxBytes or sizeleft. if sizeleft is returned that means it would crash? i guess it should be std::min so always the min value than maxbytes. that would also be inclusive to equal also if both sizeleft and maxbytes are equal..
Yes, should be std::min, I'll edit the answer to reflect that. Thanks for the spot!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.