Table of Contents (top down ↓)
- Use the iostream library of the Standard C++ to open an ifstream for reading a file.
- Use seekg to position the get pointer at the end of the file. Technically at 0 bytes from the end, ios::end.
- Next read its position using tellg. The function tellg returns the position from the start of the file in characters [unsigned char, i.e., bytes]. The value that tellg returns is the required file size.
- This program can handle the largest file size that your OS, 32bit/64bit, can support. Hence, this method works on all file sizes.
The source code in C++
Compile using any C++ compiler. The code has self-explanatory comments.
#include <iostream> #include <fstream> using namespace std; int main() { // "C:\\Users\\Home\\Desktop\\cp.pdf" const char* path = "path-to-file"; // create an iftream ifstream ifs(path); // if not success return if (!ifs.is_open()) { cout << "File not found."; return -1; } // position the pointer to the end ifs.seekg(0, ios::end); // now print the file pointer // position - the size is in // bytes cout << ifs.tellg() << endl; return 0; }
Comments and Discussion
Leave your comments on the youtube comments box.
This Blog Post/Article "C++ Program to determine file size with just three lines of code" by Parveen is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.