How can I get a file\\\'s size in C++?



In C++, the file size determines the total number of bytes. To get the file size, we can take reference of the fstream header which contains various functions such as in_file(), seekg(), and tellg().

Example

Input:
The file name is tp.txt
content- "Hello Tutorialspoint"
Output:
Size of the file is 22 bytes

Example

Input:
The file name is testfile.txt
content- "Hello Tutorialspoint"
Output:
File size is 27 bytes

Now, we will demonstrate the C++ programs of the above two examples using file handling.

Getting File Size in C++

The short form of fstream header is file stream which is used for reading and writing into the files.For example, it can create files, write information to files, and read information from files.

Syntax

Following are the syntaxes of fstream header file:

ifstream in_file("file_name.txt", ios::binary);
Or,
seekg()
Or,
tellg()

Here,

  • in_file("file_name.txt", ios::binary);: It opens the files in a binary mode so the bytes are easily readable and stored.
  • seekg(): It moves the read pointer to a specific location of a file.
  • tellg(): It return the current pointer of the position and determine the file size.

Example 1

In this example, we open the file in binary mode and then move the read pointer to the end of the file. By using tellg() with in_file(), we get the position of the pointer that means file size. So, this way we can display the result.

#include<iostream>
#include<fstream>
using namespace std;
int main() {
   ifstream in_file("tp.txt", ios::binary);
   in_file.seekg(0, ios::end);
   int file_size = in_file.tellg();
   cout<<"Size of the file is"<<" "<< file_size<<" "<<"bytes";
}

The above code produces the following result:

Size of the file is 22 bytes

Example 2

In this example, we open the file in the binary mode say (ios::binary) that jumps in the end and uses the file pointer to calculate the file size in bytes. Then we use the if-statement to handle the error while opening a file. Next, it displays the file size and closes it.

#include<iostream>
#include<fstream>
using namespace std;

int main() {
   ifstream in_file("testfile.txt", ios::binary);

   if (!in_file) {
       cerr << "Error: Cannot open file." << endl;
       return 1;
   }
   
   // Move to end
   in_file.seekg(0, ios::end);            
	
   // Get the file size
   streampos file_size = in_file.tellg(); 
   cout << "File size is " << file_size << " bytes" << endl;

   // close the file
   in_file.close();
   return 0;
}

The above code produces the following result:

File size is 27 bytes
Updated on: 2025-07-01T15:07:34+05:30

15K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements