In C++, we often need to determine the size of a file which is the number of bytes in a file. This is done for various applications, such as file processing or validation. In this article, we will learn how to get the file size in C++.
Example:
Input:
FilePath = "C:/Users/Desktop/myFile.txt"
Output:
5 Bytes // myFile.txt contains "Hello"
How to Get a File's Size in C++?
In C++17 and later, we can use the std::filesystem::file_size() function from the std::filesystem library to get the size of a file. This function returns the size of the file in bytes, which can later be used for processing. It is a standalone function so we can call it directly by passing the path of the file as a parameter to the file_size() function.
C++ Program to Get File Size
The below program demonstrates how we can get a file size in C++.
// C++ Program to demonstrate how we can get a file
// size from a file path
#include <filesystem>
#include <iostream>
using namespace std;
int main()
{
// Define a path object representing the file path.
filesystem::path filePath
= "C:/Users/Desktop/myFile.txt";
// Print the file size using the file_size() function
// of the filesystem library.
cout << "File size is: "
<< filesystem::file_size(filePath) << " bytes"
<< endl;
return 0;
}
Output
File size is: 5 bytes
Note: file_size() is implemented using stat() on POSIX systems and GetFileSizeEx() on Windows, so the returned value reflects the logical file size in bytes, not the on-disk allocated size. Due to filesystem compression, sparse files, or platform/tool differences, this may not always match what some command-line tools report.
Note: The file_size() function works only in C++17 and later. If the file does not exist, it will throw a filesystem::filesystem_error exception.