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


Getting File Size in C++

Recommended Posts

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 this post

Link to post
Share on other sites
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();
cout << "size of " << filename;
cout << " is " << (m-l) << " bytes.\n";
return 0;

Share this post

Link to post
Share on other sites