远程下载文件,并将http 头信息存放内存中以及文件大小等相关信息:
1 #include <stdio.h> 2 #include <curl/curl.h> 3 #include <stdlib.h> 4 #include <string.h> 5 6 struct MemoryStruct { 7 char* memory; 8 size_t allsize; 9 }; 10 11 static size_t WriteMemoryCallback(void* contents, size_t _size, size_t nmemb, void* userp) 12 { 13 size_t realsize = _size * nmemb; 14 struct MemoryStruct *mem = (struct MemoryStruct*)userp; 15 16 mem->memory = (char*)realloc(mem->memory, mem->allsize + realsize + 1); 17 if(mem->memory == NULL){ 18 printf("realloc error...\n"); 19 return 0; 20 } 21 22 memcpy(&(mem->memory[mem->allsize]), contents, realsize); 23 mem->allsize += realsize; 24 mem->memory[mem->allsize] = 0; 25 26 return realsize; 27 } 28 29 30 size_t write_data(char* buffer, size_t size, size_t items, void* outstream) 31 { 32 int written = fwrite(buffer, size, items, (FILE*)(outstream)); 33 return written; 34 } 35 36 double get_download_size(char* url){ 37 CURL* curl; 38 CURLcode res; 39 double size = 0.0; 40 int httpcode=0; 41 FILE* fd = fopen("./aaa.txt", "wb+"); 42 char *type = (char*)malloc(32); 43 struct MemoryStruct chunk; 44 chunk.memory = (char*)malloc(1); 45 chunk.allsize = 0; 46 47 48 49 curl = curl_easy_init(); 50 curl_easy_setopt(curl, CURLOPT_URL, url); 51 //curl_easy_setopt(curl, CURLOPT_NOBODY, 1L); 52 curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 0); //不跳转 53 curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT_MS, 3000); 54 curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void*)fd); 55 curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data); 56 57 curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, WriteMemoryCallback); 58 curl_easy_setopt(curl, CURLOPT_HEADERDATA, (void*)&chunk); 59 60 res = curl_easy_perform(curl); 61 if(res != CURLE_OK){ 62 fprintf(stderr, "curl_easy_getinfo() failed: %s\n", curl_easy_strerror(res)); 63 } 64 res = curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &httpcode); 65 if(res != CURLE_OK || httpcode != 200 ){ 66 fprintf(stdout, "httpcode error!\n"); 67 } 68 res = curl_easy_getinfo(curl, CURLINFO_CONTENT_LENGTH_DOWNLOAD, &size); 69 if(res != CURLE_OK ){ 70 fprintf(stdout, "httpcode xxxerror!\n"); 71 } 72 73 res = curl_easy_getinfo(curl, CURLINFO_CONTENT_TYPE, &type); 74 if(res != CURLE_OK ){ 75 fprintf(stdout, "TYPE xxxerror!\n"); 76 } 77 printf("type:\n%s\n", type); 78 printf("header:\n%s\n", chunk.memory); 79 fclose(fd); 80 free(chunk.memory); 81 curl_easy_cleanup(curl); 82 83 return size; 84 } 85 86 int main(int argc, char* argv[]) 87 { 88 char url[] = "http://www.fastcgi.com/dist/fcgi.tar.gz"; 89 90 double filesize = get_download_size(url); 91 printf("[%0.0lf] %s\n", filesize, url); 92 return 0; 93 }
时间: 2024-10-13 10:55:54