libcurl的文档中有getinmemory.c这个例子,把下载的网页写入自己定义的一个memorystruct中,看了这个例子的做法,它需要自己照顾内存的开辟,特别是需要在curl_easy_perform的调用函数中释放已开辟的内存,很不利于函数的封装,而且应用于multihandle的时候,运行时会出莫名其妙的assert错误。因此改写了一下,将下载的内容放入stl的string中,这样根本不需要自己照顾内存的开辟和释放。源代码如下:
#include "curl.h"
using namespace std;
static char errorBuffer[CURL_ERROR_SIZE];
static int writer(char *, size_t, size_t, string *);
static bool init(CURL *&, char *,string *);
int main()
{
CURL *conn = NULL;
CURLcode code;
string buffer;
curl_global_init(CURL_GLOBAL_DEFAULT);
char* url="http://cool.haxx.se/";
if (!init(conn,url,&buffer ))
{
fprintf(stderr, "Connection initializion failed\n");
exit(EXIT_FAILURE);
}
code = curl_easy_perform(conn);
if (code != CURLE_OK)
{
fprintf(stderr, "Failed to get '%s' [%s]\n", url, errorBuffer);
exit(EXIT_FAILURE);
}
curl_easy_cleanup(conn);
printf("%s\n",buffer.c_str());
return 0;
}
static bool init(CURL *&conn, char *url,string *p_buffer)
{
CURLcode code;
conn = curl_easy_init();
if (conn == NULL)
{
fprintf(stderr, "Failed to create CURL connection\n");
exit(EXIT_FAILURE);
}
code = curl_easy_setopt(conn, CURLOPT_ERRORBUFFER, errorBuffer);
if (code != CURLE_OK)
{
fprintf(stderr, "Failed to set error buffer [%d]\n", code);
return false;
}
code = curl_easy_setopt(conn, CURLOPT_URL, url);
if (code != CURLE_OK)
{
fprintf(stderr, "Failed to set URL [%s]\n", errorBuffer);
return false;
}
code = curl_easy_setopt(conn, CURLOPT_FOLLOWLOCATION, 1);
if (code != CURLE_OK)
{
fprintf(stderr, "Failed to set redirect option [%s]\n", errorBuffer);
return false;
}
code = curl_easy_setopt(conn, CURLOPT_WRITEFUNCTION, writer);
if (code != CURLE_OK)
{
fprintf(stderr, "Failed to set writer [%s]\n", errorBuffer);
return false;
}
code = curl_easy_setopt(conn, CURLOPT_WRITEDATA, p_buffer);
if (code != CURLE_OK)
{
fprintf(stderr, "Failed to set write data [%s]\n", errorBuffer);
return false;
}
return true;
}
static int writer(char *data, size_t size, size_t nmemb, string *writerData)
{
unsigned long sizes = size * nmemb;
if (writerData == NULL) return 0;
writerData->append(data, sizes);
return sizes;
}