远程下载文件,并将http 头信息存放内存中以及文件大小等相关信息:

 #include <stdio.h>
#include <curl/curl.h>
#include <stdlib.h>
#include <string.h> struct MemoryStruct {
char* memory;
size_t allsize;
}; static size_t WriteMemoryCallback(void* contents, size_t _size, size_t nmemb, void* userp)
{
size_t realsize = _size * nmemb;
struct MemoryStruct *mem = (struct MemoryStruct*)userp; mem->memory = (char*)realloc(mem->memory, mem->allsize + realsize + );
if(mem->memory == NULL){
printf("realloc error...\n");
return ;
} memcpy(&(mem->memory[mem->allsize]), contents, realsize);
mem->allsize += realsize;
mem->memory[mem->allsize] = ; return realsize;
} size_t write_data(char* buffer, size_t size, size_t items, void* outstream)
{
int written = fwrite(buffer, size, items, (FILE*)(outstream));
return written;
} double get_download_size(char* url){
CURL* curl;
CURLcode res;
double size = 0.0;
int httpcode=;
FILE* fd = fopen("./aaa.txt", "wb+");
char *type = (char*)malloc();
struct MemoryStruct chunk;
chunk.memory = (char*)malloc();
chunk.allsize = ; curl = curl_easy_init();
curl_easy_setopt(curl, CURLOPT_URL, url);
//curl_easy_setopt(curl, CURLOPT_NOBODY, 1L);
curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, ); //不跳转
curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT_MS, );
curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void*)fd);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data); curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, WriteMemoryCallback);
curl_easy_setopt(curl, CURLOPT_HEADERDATA, (void*)&chunk); res = curl_easy_perform(curl);
if(res != CURLE_OK){
fprintf(stderr, "curl_easy_getinfo() failed: %s\n", curl_easy_strerror(res));
}
res = curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &httpcode);
if(res != CURLE_OK || httpcode != ){
fprintf(stdout, "httpcode error!\n");
}
res = curl_easy_getinfo(curl, CURLINFO_CONTENT_LENGTH_DOWNLOAD, &size);
if(res != CURLE_OK ){
fprintf(stdout, "httpcode xxxerror!\n");
} res = curl_easy_getinfo(curl, CURLINFO_CONTENT_TYPE, &type);
if(res != CURLE_OK ){
fprintf(stdout, "TYPE xxxerror!\n");
}
printf("type:\n%s\n", type);
printf("header:\n%s\n", chunk.memory);
fclose(fd);
free(chunk.memory);
curl_easy_cleanup(curl); return size;
} int main(int argc, char* argv[])
{
char url[] = "http://www.fastcgi.com/dist/fcgi.tar.gz"; double filesize = get_download_size(url);
printf("[%0.0lf] %s\n", filesize, url);
return ;
}
05-11 11:09