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?
views:
351answers:
2
+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
2010-03-09 14:04:41
awesome! thanks =)
warren
2010-03-09 14:06:13
changed size_t to streampos.
AraK
2010-03-09 14:09:23
Out of interest, is the first call to `tellg` not guaranteed to return 0?
Steve Jessop
2010-03-09 14:45:14
@Steve Honestly, I am not sure. I couldn't figure it out from the standards :(
AraK
2010-03-09 15:00:20
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
2010-03-09 19:18:40
+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
2010-03-09 14:06:22
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
2010-03-09 14:46:32