C++17 brings std::filesystem
which streamlines a lot of tasks on files and directories. Not only you can quickly get file size, its attributes, but also create new directories, iterate through files, work with path objects.
The new library gives us two functions that we can use:
std::uintmax_t std::filesystem::file_size( const std::filesystem::path& p );
std::uintmax_t std::filesystem::directory_entry::file_size() const;
The first function is a free function in std::filesystem
, the second one is a method in directory_entry
.
Each method also has an overload, as it can throw an exception or return an error code (through an output parameter).
Below is the detail code explaining all the possible cases.
#include <chrono>
#include <filesystem>
#include <iostream>
namespace fs = std::filesystem;
int main(int argc, char* argv[])
{
try
{
const auto fsize = fs::file_size("a.out");
std::cout << fsize << '\n';
}
catch (const fs::filesystem_error& err)
{
std::cerr << "filesystem error! " << err.what() << '\n';
if (!err.path1().empty())
std::cerr << "path1: " << err.path1().string() << '\n';
if (!err.path2().empty())
std::cerr << "path2: " << err.path2().string() << '\n';
}
catch (const std::exception& ex)
{
std::cerr << "general exception: " << ex.what() << '\n';
}
// using error_code
std::error_code ec{};
auto size = std::filesystem::file_size("a.out", ec);
if (ec == std::error_code{})
std::cout << "size: " << size << '\n';
else
std::cout << "error when accessing test file, size is: "
<< size << " message: " << ec.message() << '\n';
}
tellg
problems. The only one worth bothering with is the fourth one, and that one's not great, since it talks too much aboutofstream
, in both the question and its answers. This one is far better at expressing the intent than the others (except for the first, which is oddly closed). – Correystat(2)
anyways? Has it grown too old or what? – Definitivestat(2)
It's not part of the language standard. – Canaraduplicate
tag. – Hygrograph<filesystem>
is used, but as Nicol implied, it was perhaps too embedded in that questions rotating log functionality to be of much use here. – Chicago