2012-10-09 66 views
1

幾個議題(見Using C++ filestreams (fstream), how can you determine the size of a file?C++: Getting incorrect file size)如何衡量文件大小計算開始,像該文件的末尾之間的區別:而不是在一開始打開文件的獲取文件大小與std :: ios :: ate?

std::streampos fileSize(const char* filePath){ 

    std::streampos fsize = 0; 
    std::ifstream file(filePath, std::ios::binary); 

    fsize = file.tellg(); 
    file.seekg(0, std::ios::end); 
    fsize = file.tellg() - fsize; 
    file.close(); 

    return fsize; 
} 

但是,我們可以在最後打開它,然後採取如下措施:

std::streampos fileSize(const char* filePath){ 

    std::ifstream file(filePath, std::ios::ate | std::ios::binary); 
    std::streampos fsize = file.tellg(); 
    file.close(); 

    return fsize; 
} 

它會工作嗎?如果不是爲什麼?

+0

只是一個側面說明,調用'關閉'是不必要的。 –

+0

可能會工作,但不知道這是獲得文件大小的最佳方式。 – goji

+0

我通常如果我需要獲得文件大小隻是打電話,如: 'std :: ifstream file(filepath,std :: ios :: ate | std :: ios :: binary);' 'int fileLength = 0 ;' 'file.seekg(0,std :: ios :: end);' 'fileLength = file.tellg();' 'file.seekg(0,std :: ios :: beg);' 'if(fileLength == -1){//錯誤的東西在這裏}' 等等。 我相信,在流的位置的不同,雖然是它是一個內部字符數組,那麼位置1,可以抵消0。雖然,這部分我不積極有關 – M4rc

回答

1

它應該工作得很好。 C++標準說,大約std::ios::ate

ate - 開放,並努力打開

沒有理由會失敗後立即結束時手動開,然後捉迷藏會成功。無論哪種情況,tellg都是相同的。