在上一个帖子 Building curl 7.46.0之后,我测试了以下示例代码,该代码编译没有错误,但在我的控制台上没有打印任何内容。
#include <iostream>
#include <WinSock2.h>
#include <stdio.h>
#include <curl/curl.h>
int main(void) {
CURL *curl;
CURLcode res;
curl = curl_easy_init();
if (curl) {
curl_easy_setopt(curl, CURLOPT_URL, "http://www.cnn.com/");
system("pause");
res = curl_easy_perform(curl);
/* always cleanup */ curl_easy_cleanup(curl);
}
//system("pause");
return 0;
}
这个结果是否是由于安装libcurl
时采用的设置?事实上,我使用了libcurl.dll
和libcurl.lib
:
1 - (发布模式):nmake /f Makefile.vc mode=dll VC=12
2 - (调试模式):nmake /f Makefile.vc mode=dll VC=12 DEBUG=yes
最佳,
期望:像
这样的东西[编辑] :有效代码
#include<string>
#include <WinSock2.h>
#include <stdio.h>
#include <curl/curl.h>
int main(void)
{
CURL *curl = curl_easy_init();
if (curl) {
CURLcode res;
curl_easy_setopt(curl, CURLOPT_URL, "http://edition.cnn.com/");
res = curl_easy_perform(curl);
curl_easy_cleanup(curl);
system("pause");
}
}
答案 0 :(得分:0)
作为
的文件http://curl.haxx.se/libcurl/c/curl_easy_setopt.html
建议,您需要指定一个将写入的回调函数 html到一些缓冲区。然后,您可以使用该缓冲区来打印 内容。这是你如何做到的:
#include <iostream>
#include <WinSock2.h>
#include <stdio.h>
#include <curl/curl.h>
#include <string>
static size_t getHtmlCallback(void *contents, size_t size, size_t nmemb, void *ptr)
{
// Cast ptr to std::string pointer and append contents to that string
((std::string*)ptr)->append((char*)contents, size * nmemb);
return size * nmemb;
}
int main(void)
{
CURL *curl;
CURLcode res;
std::string htmlBuffer;
curl = curl_easy_init();
if(curl) {
curl_easy_setopt(curl, CURLOPT_URL, "http://www.cnn.com/");
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, getHtmlCallback);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &htmlBuffer);
res = curl_easy_perform(curl);
if(CURLE_OK == res)
{
std::cout << htmlBuffer << std::endl;
}
curl_easy_cleanup(curl);
}
return 0;
}
答案 1 :(得分:0)
libcurl
似乎失败了(即curl_easy_init
正在返回NULL
)。遗憾的是,根据http://curl.haxx.se/mail/lib-2009-11/0243.html,您必须使用调试器来找出原因。