Download the file remotely and store the HTTP header information in memory and the size of the file:
1#include <stdio.h>2#include <curl/curl.h>3#include <stdlib.h>4#include <string.h>5 6 structmemorystruct {7 Char*memory;8 size_t allsize;9 };Ten One Staticsize_t Writememorycallback (void* Contents, size_t _size, size_t nmemb,void*userp) A { -size_t realsize = _size *Nmemb; - structMemorystruct *mem = (structmemorystruct*) Userp; the -Mem->memory = (Char*) realloc (mem->memory, mem->allsize + realsize +1); - if(Mem->memory = =NULL) { -printf"realloc error...\n"); + return 0; - } + Amemcpy (& (mem->memory[mem->allsize]), contents, realsize); atMem->allsize + =realsize; -Mem->memory[mem->allsize] =0; - - returnrealsize; - } - in -size_t Write_data (Char* Buffer, size_t size, size_t items,void*OutStream) to { + intWritten = fwrite (buffer, size, items, (file*) (OutStream)); - returnwritten; the } * $ DoubleGet_download_size (Char*URL) {Panax Notoginsengcurl*Curl; - Curlcode Res; the DoubleSize =0.0; + intHttpcode=0; Afile* FD = fopen ("./aaa.txt","wb+"); the Char*type = (Char*) malloc ( +); + structmemorystruct Chunk; -Chunk.memory = (Char*) malloc (1); $Chunk.allsize =0; $ - - theCurl =curl_easy_init (); - curl_easy_setopt (Curl, Curlopt_url, URL);Wuyi //curl_easy_setopt (Curl, Curlopt_nobody, 1L); theCurl_easy_setopt (Curl, Curlopt_followlocation,0);//do not jump -Curl_easy_setopt (Curl, Curlopt_connecttimeout_ms, the); WuCurl_easy_setopt (Curl, Curlopt_writedata, (void*) FD); - curl_easy_setopt (Curl, curlopt_writefunction, write_data); About $ curl_easy_setopt (Curl, curlopt_headerfunction, writememorycallback); -Curl_easy_setopt (Curl, Curlopt_headerdata, (void*) &chunk); - -res =curl_easy_perform (curl); A if(Res! =CURLE_OK) { +fprintf (stderr,"Curl_easy_getinfo () failed:%s\n", Curl_easy_strerror (res)); the } -res = Curl_easy_getinfo (curl, Curlinfo_response_code, &httpcode); $ if(res! = CURLE_OK | | Httpcode! = $ ){ thefprintf (stdout,"Httpcode error!\n"); the } theres = Curl_easy_getinfo (curl, Curlinfo_content_length_download, &size); the if(Res! =CURLE_OK) { -fprintf (stdout,"Httpcode xxxerror!\n"); in } the theres = Curl_easy_getinfo (curl, Curlinfo_content_type, &type); About if(Res! =CURLE_OK) { thefprintf (stdout,"TYPE xxxerror!\n"); the } theprintf"type:\n%s\n", type); +printf"header:\n%s\n", chunk.memory); - fclose (FD); the Free (chunk.memory); Bayi curl_easy_cleanup (curl); the the returnsize; - } - the intMainintargcChar*argv[]) the { the CharUrl[] ="http://www.fastcgi.com/dist/fcgi.tar.gz"; the - DoubleFileSize =get_download_size (URL); theprintf"[%0.0LF]%s\n", filesize, url); the return 0; the}
Libcurl Use Example