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;
}
它會工作嗎?如果不是爲什麼?
只是一個側面說明,調用'關閉'是不必要的。 –
可能會工作,但不知道這是獲得文件大小的最佳方式。 – goji
我通常如果我需要獲得文件大小隻是打電話,如: '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