C++ Program to determine file size with just three lines of code

This is a C++ program that prints the size of any file in bytes. Only three lines of code required! We use the ifstream class to open the file for reading. Then position the file pointer to the end. Lastly, read the position to obtain the file size!
(Rev. 31-Oct-2024)

Categories | About |     |  

Parveen,

Table of Contents (top down ↓)

  1. Use the iostream library of the Standard C++ to open an ifstream for reading a file.
  2. Use seekg to position the get pointer at the end of the file. Technically at 0 bytes from the end, ios::end.
  3. 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.
  4. 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.