1

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 ?

8
  • Just a side note, the calls to close are unnecessary. Commented Oct 9, 2012 at 1:50
  • Probably would work, not sure it's the best way to get a file size though. Commented Oct 9, 2012 at 1:52
  • I usually if I need to get file size just make calls as so: 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 about Commented Oct 9, 2012 at 1:52
  • @SethCarnegie : why are the call to close unnecessary ? Commented Oct 9, 2012 at 1:54
  • Because ifstream is an RAII object that closes its file when it is destroyed. Commented Oct 9, 2012 at 1:57

1 Answer 1

2

It should work just fine. The C++ standard says about std::ios::ate

ate - open and seek to end immediately after opening

There's no reason it would fail when a manual open-then-seek would succeed. And tellg is the same in either case.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.