来自http://tunps.com/libcurl-sample-program
#define CURL_STATICLIB
#define _CRT_SECURE_NO_WARNINGS
#define _CRT_SECURE_NO_DEPRECATE
#pragma comment(lib,"ws2_32.lib")
#pragma comment(lib,"D:\\win32dev\\curl-7.19.0\\lib\\Debug\\curllib.lib")
/* Start of test program */
#include <stdio.h>
#include <stdlib.h>
#include <curl/curl.h>
#include <curl/types.h>
#include <curl/easy.h>
size_t write_data(void *ptr, size_t size, size_t nmemb, FILE *stream)
{
static int first_time=1;
char outfilename[FILENAME_MAX] = "body.html";
static FILE *outfile;
size_t written;
if (first_time) {
first_time = 0;
outfile = fopen(outfilename,"w+");
if (outfile == NULL) {
return -1;
}
fprintf(stderr,"The body is <%s>\n",outfilename);
}
written = fwrite(ptr,size,nmemb,outfile);
return written;
}
int main(int argc, char **argv)
{
CURL *curl_handle;
char headerfilename[FILENAME_MAX] = "head.html";
FILE *headerfile;
int rc=0;
curl_handle = curl_easy_init();
curl_easy_setopt(curl_handle, CURLOPT_URL, "http://www.sina.com.cn");
curl_easy_setopt(curl_handle, CURLOPT_NOPROGRESS ,1);
curl_easy_setopt(curl_handle, CURLOPT_WRITEFUNCTION,&write_data);
headerfile = fopen(headerfilename,"w");
if (headerfile == NULL) {
curl_easy_cleanup(curl_handle);
return -1;
}
curl_easy_setopt(curl_handle, CURLOPT_WRITEHEADER ,headerfile);
curl_easy_perform(curl_handle);
printf("The head is <%s>\n",headerfilename);
fclose(headerfile);
curl_easy_cleanup(curl_handle);
return 0;
}
/* End of test program */
将获取的html文件内容保存在body.html。保存的方法是curl_easy_setopt函数中设置CURLOPT_WRITEFUNCTION的回调函数为write_data。
在write_data这个回调函数中需要注意的是,curl碰到web文件过大的情况会分段获取内容
size_t write_data(void *ptr, size_t size, size_t nmemb, FILE *stream)
参数ptr是指向分段下载内容的指针。size是内容大小,mmemb指定单位一般是1(Byte)。stream就是CURLOPT_WRITEDATA指定的指针。如果要讲所有html内容保存在buffer中,可以strcat(stream,ptr);就可以了。