【发布时间】:2018-03-30 22:34:34
【问题描述】:
在我的 c 程序中,我尝试使用 libcurl 从本地网络服务器获取数据。 这是我的代码:
int main() {
CURL *curl;
CURLcode res;
curl_global_init(CURL_GLOBAL_ALL);
curl = curl_easy_init();
curl_easy_setopt( curl, CURLOPT_URL, "localhost:3000/employees/2" );
curl_easy_setopt( curl, CURLOPT_WRITEFUNCTION, write_data );
res = curl_easy_perform(curl);
...
}
回调函数write_data如下所示:
size_t write_data(void *buffer, size_t size, size_t nmemb, void *userp) {
return size;
}
当 libcurl 调用我的回调函数“缓冲区”包含预期的数据。 但我面临错误:
Failed writing body ( 1!= 105)
Closing connection
curl_easy_perform() failed: res = 23
error = failed writing received data to disk/application
当我不设置回调函数时它可以工作。
卷曲教程说: libcurl 提供了自己的默认内部回调,如果您不使用 CURLOPT_WRITEFUNCTION 设置回调,它将处理数据。然后它会将接收到的数据简单地输出到标准输出。
但由于我设置了回调,我不明白为什么 curl 显然仍然试图写入我的数据?
我做错了什么?
【问题讨论】:
-
可能你没有权限?有什么方法可以从该错误中获取更多诊断信息?
-
您应该返回
size还是nmemb?这就是采取鸭子可以提供帮助的地方......见How to debug small programs -
阅读文档。您必须返回
size * nitems;。