#### Archived

This topic is now archived and is closed to further replies.

# Getting File Size in C++

## Recommended Posts

Shmiznac    122
Do the fstream classes include a way to get the size of a binary file? Or do I have to use the standard _filelength or stat C functions?

##### Share on other sites
Fruny    1658
No, they don't. Theoretically, you don't need them, since you can load the whole file in a dynamic array (vector) without knowing the size in advance.

    #include <fstream>#include <vector>#include <iterator>using namespace std;ifstream ifs( "filename", ios::binary );vector<char> data( istreambuf_iterator<char>( ifs ),                   istreambuf_iterator<char>() );size_t length = data.size();

Disadvantage here if you just wanted to check the file size is that you need to load it first, which not only is costly, but may also be impossible due to read permission issues.

And streams, just like files, don't necessary have a size (e.g. sockets, pipes, and special device files like /dev/urandom or /dev/zero).

It is possible to use seekg/tellg just like fseek/ftell, but the results are highly unreliable - usually due to newline translation, but all the manuals I have explicitely state that the value returned by tell-like functions are only meaningful for seek-like functions, not as numeric values.

Oh, and watch out, stat() is POSIX standard, not ISO C.
And I don't know of a _filelength function;
To my knowledge no standard function starts with an underscore, they usually are extensions.

[ Start Here ! | How To Ask Smart Questions | Recommended C++ Books | C++ FAQ Lite | Function Ptrs | CppTips Archive ]
[ Header Files | File Format Docs | LNK2001 | C++ STL Doc | STLPort | Free C++ IDE | Boost C++ Lib | MSVC6 Lib Fixes ]

[edited by - Fruny on March 8, 2003 2:32:46 AM]

##### Share on other sites
Shmiznac    122
Hmm...nice use of a vector there, didn''t know you could do that. Funny how I really dislike the C++ file I/O compared to the C version. Anyway, thanks for the info.

##### Share on other sites
billybob    134
you can easily use stdio in C++ also, you don''t have to use iostream. i MUCH prefer fopen/fread/fwrite/fclose to fstream. just include stdio.h

##### Share on other sites
Shmiznac    122
Yeah I use the C file functions a lot, but when you''re supposed to be programming in C++ it just feels so...dirty . It''s a shame fstream sucks so much.

##### Share on other sites
mr_dejao    122
I haven''t tested this myself, just coped it from a site off the net for ya (not at my linux machine so I can''t compile it, and I am too tired to debug it ) - I am sure you can work it out.

// obtaining file size#include <iostream.h>#include <fstream.h>const char * filename = "example.txt";int main () {  long l,m;  ifstream file (filename, ios::in|ios::binary);  l = file.tellg();  file.seekg (0, ios::end);  m = file.tellg();  file.close();  cout << "size of " << filename;  cout << " is " << (m-l) << " bytes.\n";  return 0;}