且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在libcurl中发送长PUT数据而不使用文件指针?

更新时间:2022-10-29 13:06:07

You will still want to use CURLOPT_READDATA, however if you use CURLOPT_READFUNCTION, it can be any user-specified pointer. You can create a simple structure like:

struct put_data
{
  char *data;
  size_t len;
};

where data is the PUT data and len is the length (remaining).

Then, set CURLOPT_READDATA to a pointer to an initialized instance of that structure. You will be passed it in CURLOPT_READFUNCTION as userdata. In that function, do something like:

size_t curl_size = nmemb * size;
size_t to_copy = (userdata->len < curl_size) ? userdata->len : curl_size;
memcpy(ptr, userdata->data, to_copy);
userdata->len -= to_copy;
userdata->data += to_copy;
return to_copy;

This basically figures out the amount to copy, copies it, then updates the length and pointer. On the to_copy line, we calculate the minimum because were are bounded by both the amount remaining and the size of curl's buffer. Finally, we return the number of bytes copied, as required by curl. When you're at the end of content user_data->len (and thus to_copy) will be 0. Nothing will be copied and returning 0 ends the transfer.