Several topics (see Using C++ filestreams (fstream), how can you determine the size of a file? and C++: Getting incorrect file size) on how to measure a file size compute the difference between the beginning and the end of the file like that :
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; } But instead of opening the file at the beginning, we can open it at the end and just take a measure, like that :
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; } Will it work ? And if not why ?
closeare unnecessary.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) { //error stuff here}And so on. I believe the difference in position of stream though, is it's an internal char array, so position 1, could be offset 0. Though, this part I am not positive aboutifstreamis an RAII object that closes its file when it is destroyed.