Code Yarns ‍👨‍💻
Tech BlogPersonal Blog

How to find size of file in C++

📅 2018-Feb-02 ⬩ ✍️ Ashwin Nanjappa ⬩ 🏷️ cpp, filesize ⬩ 📚 Archive

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();

© 2022 Ashwin Nanjappa • All writing under CC BY-SA license • 🐘📧