On POSIX-compliant systems such as Linux or macOS, you can use stat, while on Windows systems, you can use _stat.
#include <iostream>
#include <sys/stat.h> // On POSIX systems
int main() {
const char* filename = "example.txt";
struct stat stat_buf;
int rc = stat(filename, &stat_buf); // On Windows, use _stat
if (rc != 0) {
std::cerr << "Cannot get file size." << std::endl;
return 1;
}
std::cout << "File size: " << stat_buf.st_size << " bytes" << std::endl;
return 0;
}
Remember to replace "example.txt" with the actual name of your file. Also note that if you're writing cross-platform code, you should provide platform-specific conditionals to handle different functions for file size retrieval.
Modern C++: Using std::filesystem
With C++17 and later, you can use the std::filesystem library which simplifies file size retrieval.
Make sure that your compiler is set to use C++17 or later for the last example to work. You can usually enable this with a compiler flag like -std=c++17.