Re: Standard C++ file size???
On Oct 6, 4:33 pm, PeteOlcott <PeteOlc...@gmail.com> wrote:
On Oct 6, 5:21 am, James Kanze <james.ka...@gmail.com> wrote:
On Oct 5, 6:21 pm, Victor Bazarov <v.Abaza...@comAcast.net> wrote:
Peter Olcott wrote:
Is there any standard C++ way to determine the size of a
file before it is read?
No. The "standard C++ way" is to open the file for reading,
seek to the end of the file and get the position.
That's a frequently used method, but it certainly isn't
standard C++. There's no guarantee that the position is
convertable to an integral type, and there's no guarantee
that the integral value means anything if it is.
In practice, this will probably work under Unix, and with
binary (but not text) files under Windows. Elsewhere, who
knows?
Why would it not work for Text files under Windows? (I am
only looking for the size that can be block read into memory)
Because it doesn't. Try it:
#include <iostream>
#include <fstream>
#include <vector>
void
readAll(
char const* filename )
{
std::ifstream f( filename ) ;
if ( ! f ) {
throw "cannot open" ;
}
f.seekg( 0, std::ios::end ) ;
if ( ! f ) {
throw "seek error" ;
}
long long size = f.tellg() ;
std::cout << filename << ": size = " << size << std::endl ;
if ( size != 0 ) {
f.clear() ;
f.seekg( 0, std::ios::beg ) ;
if ( ! f ) {
throw "rewind failed" ;
}
std::vector< char > v( size ) ;
f.read( &v[ 0 ], size ) ;
if ( ! f ) {
throw "read failed" ;
}
}
}
int
main( int argc, char** argv )
{
for ( int i = 1 ; i != argc ; ++ i ) {
try {
readAll( argv[ i ] ) ;
} catch ( char const* error ) {
std::cout << argv[ i ] << ": " << error << std::endl ;
}
}
return 0 ;
}
Compile and try it on some text files. On a variant with some
extra comments, reading the source itself, I get:
readall.cc: size = 1677
under Solaris (g++ or Sun CC), but
readall.cc: size = 1733
readall.cc: read failed
under Windows (compiled with VC++).
If I open the file in binary mode, or use system level requests,
of course, I can make it work.
--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orient=E9e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S=E9mard, 78210 St.-Cyr-l'=C9cole, France, +33 (0)1 30 23 00 34