libcurl 放置数据流而不是文件

libcurl to put stream of data instead of file

我们正在使用 libcurl C API 以便通过 SFTP 发送文件。使用这样的代码可以正常工作:

....
fd = fopen(local_file_full_path.c_str(), "rb");
if (!fd)
{
    cout << "Error opening local file: " << local_file_full_path << endl;
    return -1;
}
curl_easy_setopt(curl_easy_handle, CURLOPT_UPLOAD, 1L);
curl_easy_setopt(curl_easy_handle, CURLOPT_FOLLOWLOCATION, 1);
curl_easy_setopt(curl_easy_handle, CURLOPT_READDATA, fd);
curl_easy_setopt(curl_easy_handle, CURLOPT_HTTPHEADER, headerList);

然而,这意味着即使我们有可用的数据,我们也必须将它们写入文件,然后将文件传递过来。

我想知道 libcurl 是否提供了一个选项,我们可以在其中传递数据流,例如指向数据结构的指针。如果是这样的话,有没有我可以使用的例子?这是否意味着“接收方”端需要进行更改 - 因为我们不拥有它。

您已经有了 1/2 的解决方案 - CURLOPT_READDATA . You just need to pair it with a custom callback in CURLOPT_READFUNCTION,然后您可以在 CURLOPT_READDATA 中传递一个指向现有数据的指针,并让您的回调在需要时将该数据复制到 libcurl 的缓冲区中数据。

This callback function gets called by libcurl as soon as it needs to read data in order to send it to the peer - like if you ask it to upload or post data to the server. The data area pointed at by the pointer buffer should be filled up with at most size multiplied with nitems number of bytes by your function.

Set the userdata argument with the CURLOPT_READDATA option.

如果您使用的是 POSIX 系统,您可以使用 fmemopen():

SYNOPSIS

#include <stdio.h>

FILE *fmemopen(void *restrict buf, size_t size,
       const char *restrict mode);

DESCRIPTION

The fmemopen() function shall associate the buffer given by the buf and size arguments with a stream. The buf argument shall be either a null pointer or point to a buffer that is at least size bytes long.

假设您有适当类型的 bufferbytes 变量,您的代码将如下所示:

fd = fmemopen(buffer, bytes, "rb");
if (!fd)
{
    cout << "Error opening local file: " << local_file_full_path << endl;
    return -1;
}
curl_easy_setopt(curl_easy_handle, CURLOPT_UPLOAD, 1L);
curl_easy_setopt(curl_easy_handle, CURLOPT_FOLLOWLOCATION, 1);
curl_easy_setopt(curl_easy_handle, CURLOPT_READDATA, fd);
curl_easy_setopt(curl_easy_handle, CURLOPT_HTTPHEADER, headerList);

如果您在 Windows 上 运行,请参阅 C - create file in memory。它专门解决了如何在 Windows.

上实现 fmemopen() 的功能