这是一个修改过的例子,与libcurl一起发布。我通过设置CURLOPT_write data将bodyfile传递给函数write_data。它确实将数据写入文件,但指针不等于传递给setopt的指针(curl_handle、CURLOPT_WRITEDATA、pointer)。如果我试图把指针传递给对象,而不是文件,我就会得到SIGSEGV。为什么?如何传递同一个指针?
代码:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <assert.h>

#include <curl/curl.h>
#include <curl/types.h>
#include <curl/easy.h>
FILE *bodyfile;
static size_t write_data(void *ptr, size_t size, size_t nmemb, void *stream)
{
    assert(bodyfile == (FILE*) stream); //this assertion fails, but when i comment it, code works. Why?
    int written = fwrite(ptr, size, nmemb, (FILE *)stream);
    return written;
}

int main(void)
{
    CURL *curl_handle;
    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://google.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);

    /* cleanup curl stuff */
    curl_easy_cleanup(curl_handle);

    return 0;
}

最佳答案

如果删除断言,则插入:
printf("body: %p stream: %p\n", bodyfile, stream);
写入数据,然后添加:
printf("head: %p body: %p\n", headerfile, bodyfile);
打开头文件和正文文件后,一切都将变得清晰。
发生的情况是,在流中使用headerfile多次调用write_数据,然后使用bodyfile调用一次。我猜对于头响应中的每一行,write_数据都调用一次。
curl_easy_setopt的手册页介绍了以下关于CURLOPT_HEADERFUNCTION的内容:
如果未设置此选项,或者
设置为空,但CURLOPT_HEADERDATA
(CURLOPT_WRITEHEADER)设置为
除了空以外,使用的函数
接受将使用的响应数据
相反。也就是说,它将是
用指定的函数
CURLOPT_WRITEFUNCTION,或者如果不是
指定或空-默认值,
流写入功能。

07-24 09:51
查看更多