C++ 取得檔案大小的方法
-
Compiler Specific: Visual C++
#include <sys\types.h> #include <sys\stat.h> __int64 FileSize64( const char * szFileName ) { struct __stat64 fileStat; int err = _stat64( szFileName, &fileStat ); if (0 != err) return 0; return fileStat.st_size; }
-
Non-Portable Version: stat()
#include <sys\types.h> #include <sys\stat.h> int FileSize( const char * szFileName ) { struct stat fileStat; int err = stat( szFileName, &fileStat ); if (0 != err) return 0; return fileStat.st_size; }
-
Portable Version: ifstream::tellg()
#include <fstream> int FileSize(const char* sFileName) { std::ifstream f; f.open(sFileName, std::ios_base::binary | std::ios_base::in); if (!f.good() || f.eof() || !f.is_open()) { return 0; } f.seekg(0, std::ios_base::beg); std::ifstream::pos_type begin_pos = f.tellg(); f.seekg(0, std::ios_base::end); return static_cast<int>(f.tellg() - begin_pos); }
-
Using Boost
#include <boost/filesystem/operations.hpp> boost::intmax_t file_size( const path & ph );
參考: