views:

351

answers:

2

I'm sure I've just missed this in the manual, but how do you determine the size of a file (in bytes) using C++'s istream class from the fstream header?

+7  A: 

You can seek until the end, then compute the difference:

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;
}
AraK
awesome! thanks =)
warren
changed size_t to streampos.
AraK
Out of interest, is the first call to `tellg` not guaranteed to return 0?
Steve Jessop
@Steve Honestly, I am not sure. I couldn't figure it out from the standards :(
AraK
I had to remove the subtraction aspect - but just reading `file.tellg()` after the `seekg()` gives the same byte size as is reported by the shell (running on CentOS 4 with g++ 3.4.6)
warren
+1  A: 

Like this:

  long begin, end;
  ifstream myfile ("example.txt");
  begin = myfile.tellg();
  myfile.seekg (0, ios::end);
  end = myfile.tellg();
  myfile.close();
  cout << "size: " << (end-begin) << " bytes." << endl;

Greets, Philip

Philip
You may want to use the more appropriate `std::streampos` instead of `long` as the latter may not support as large a range as the former - and `streampos` *is* more than just an integer.
RaphaelSP