我真的很喜欢这个。我已经看过如何使用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;
}
答案 0 :(得分:0)
CURLOPT_WRITEFUNCTION
应与以下原型匹配的函数指针:size_t function(char * ptr,size_t size,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 docs。