Libcurl将数据写入数组

Libcurl write data to array

本文关键字:数组 数据 Libcurl      更新时间:2023-10-16

我真的搜索过了。我看过libcurl如何下载并写入数据到文件的例子但我不知道如何写入数组

这是目前为止的代码:

static size_t write_data(void *ptr, size_t size, size_t nmemb, void *stream)
{
int written = fwrite(ptr, size, nmemb, (FILE *)stream);
return written;
}
int main(void)
{
CURL *curl_handle;
FILE *bodyfile;
static const char *headerfilename = "head.out";
FILE *headerfile;
static const char *bodyfilename = "body.out";
curl_global_init(CURL_GLOBAL_ALL);
/* init the curl session */
curl_handle = curl_easy_init();
/* set URL to get */
curl_easy_setopt(curl_handle, CURLOPT_URL,"http://example.com/");
/* no progress meter please */
curl_easy_setopt(curl_handle, CURLOPT_NOPROGRESS, 1L);
/* send all data to this function  */
curl_easy_setopt(curl_handle, CURLOPT_WRITEFUNCTION, write_data);
/* open the files */
headerfile = fopen(headerfilename,"w");
if (headerfile == NULL) {
    curl_easy_cleanup(curl_handle);
    return -1;
}
bodyfile = fopen(bodyfilename,"w");
if (bodyfile == NULL) {
    curl_easy_cleanup(curl_handle);
    return -1;
}
/* we want the headers to this file handle */
curl_easy_setopt(curl_handle,   CURLOPT_WRITEHEADER, headerfile);
/* we want the body to this file handle */
curl_easy_setopt(curl_handle, CURLOPT_WRITEDATA, bodyfile);
/* get it! */
curl_easy_perform(curl_handle);
/* close the header file */
fclose(headerfile);
fclose(bodyfile);
return 0;
}

您所需要的似乎在libcurl文档中有描述:

CURLOPT_WRITEFUNCTION

应该匹配以下原型的函数指针函数(char *ptr, size_t, size_t nmemb, void *userdata);这函数会在收到数据后立即被libcurl调用需要被拯救。[…]

也就是说你必须实现一个带有

签名的函数
size_t my_array_write(char *ptr, size_t size, size_t nmemb, void *userdata);

传递给curl:

curl_easy_setopt(curl_handle, CURLOPT_WRITEFUNCTION, my_array_write);

然而,我还没有测试它(我不知道一个更简单的方法来实现这一点)。更多信息请参见libcurl文档