cURL - 将输出放入变量?

标签 c libcurl

我目前正在使用这个 C 代码:

CURL *curl;
CURLcode res;

curl = curl_easy_init();
if (curl) {
    curl_easy_setopt(curl, CURLOPT_URL, "http://my-domain.org/");
    res = curl_easy_perform(curl);

    curl_easy_cleanup(curl);
}

它在控制台上打印输出。我怎样才能得到相同的输出,但将它读入,比如说,一个字符串? (这可能是一个基本问题,但我还不了解 libcurl API...)

感谢您的帮助!

迈克

最佳答案

您需要传递一个函数和缓冲区以将其写入缓冲区。

/* setting a callback function to return the data */
curl_easy_setopt(curl_handle, CURLOPT_WRITEFUNCTION, write_callback_func);

/* passing the pointer to the response as the callback parameter */
curl_easy_setopt(curl_handle, CURLOPT_WRITEDATA, &response);


/* the function to invoke as the data recieved */
size_t static write_callback_func(void *buffer,
                        size_t size,
                        size_t nmemb,
                        void *userp)
{
    char **response_ptr =  (char**)userp;

    /* assuming the response is a string */
    *response_ptr = strndup(buffer, (size_t)(size *nmemb));

}

请查看更多信息here .

关于cURL - 将输出放入变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2577654/

相关文章:

c++ - 如何为 Windows Phone 8 安装 libcurl

c - 了解 file_operations 的 loff_t *offp

c - libcurl 什么时候关闭由 OPEN_SOCKETFUNCTION open_callback 打开的套接字?

c - 使用 SSE 实现上述逻辑的可能性

c - 如何严格使用 fgets 函数以大写/小写字母打印字符串?

c - 在 C 中,如何使用 libcurl 将 HTTP 响应读入字符串?

objective-c - libcURL 代码不工作,说我正在上传到没有文件名的服务器

c++ - Libcurl 返回损坏的数据

c++ - 结构中的函数指针

c - 从汇编逆向工程优化的 C 代码