How to find size of file in C++

A common trick to find the size of a file in C++ is to open it as a stream and seek to the end. You can then ask the stream to tell you the current position in the stream and that would be the number of bytes in the file.

Solution 1

Open a file in binary mode and immediately move to the end. Then ask for the position:

std::ifstream in_file("foobar.bin", std::ios::binary | std::ios::ate);
int file_size = in_file.tellg();

Solution 2

std::ifstream in_file("foobar.bin", std::ios::binary);
in_file.seekg(0, std::ios::end);
int file_size = in_file.tellg();
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s