libcurl远程获取文件大小源码
這是一個(gè)簡(jiǎn)單的獲取遠(yuǎn)程文件大小的源碼,我們可以改寫為大批量異步的形式.
#include <stdio.h>
#include <curl/curl.h>size_t get_size_struct(void* ptr, size_t size, size_t nmemb, void* data){return (size_t)(size * nmemb);
}double get_download_size(char* url){CURL* curl;CURLcode res;double size = 0.0;curl = curl_easy_init();curl_easy_setopt(curl, CURLOPT_URL, url);curl_easy_setopt(curl, CURLOPT_NOBODY, 1L);curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, get_size_struct);curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);res = curl_easy_perform(curl);res = curl_easy_getinfo(curl, CURLINFO_CONTENT_LENGTH_DOWNLOAD, &size);if(res != CURLE_OK){fprintf(stderr, "curl_easy_getinfo() failed: %s\n", curl_easy_strerror(res));}curl_easy_cleanup(curl);return size;
}int main(int argc, char* argv[]){char url[] = "http://cdimage.ubuntu.com/releases/14.04/release/ubuntu-14.04-desktop-amd64+mac.iso";double filesize = get_download_size(url);printf("[%0.0lf] %s\n", filesize, url);return 0;
}
下面是批量判斷代碼實(shí)現(xiàn)的結(jié)果
分析和思考:
獲取遠(yuǎn)程文件大小中遇到的問(wèn)題
CURLINFO_CONTENT_LENGTH_DOWNLOAD
Pass a pointer to a double to receive the content-length of the download. This is the value read from the Content-Length: field. Since 7.19.4, this returns -1 if the size isn't known.
使用這個(gè)項(xiàng)獲取文件大小,比較受限制,它要求必須在http Response header中帶有Content-Length頭域才可以。如果沒有就獲取不了該長(zhǎng)度。而我們知道,如果是chunked傳輸?shù)臅r(shí)候,就肯定沒有content-length頭。所以還需要尋找其他的解決方法。
測(cè)試發(fā)現(xiàn),使用這種方法,對(duì)大文件(超過(guò)2M)的長(zhǎng)度獲取還是準(zhǔn)確的,但是對(duì)html頁(yè)面的小文件,因?yàn)榭赡苁莋zip或是chunk傳輸?shù)?#xff0c;獲取的長(zhǎng)度僅只能作為參考。比如未gzip壓縮和gzip壓縮的傳輸方式獲取的長(zhǎng)度肯定不是一樣的。
采用這種方法,只能限制大,不限制小,因?yàn)樾∥募@取不精確。
總結(jié)
以上是生活随笔為你收集整理的libcurl远程获取文件大小源码的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: printf格式化输出几点注记
- 下一篇: libcurl 编程进度条和range请