Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

std::filesystem::file_size: regular-file size in bytes

std::filesystem::file_size returns a uintmax_t regular-file size in bytes and reports an error for a missing path.

Version: C++23

Syntax

std::uintmax_t std::filesystem::file_size(
    const std::filesystem::path& p);

std::uintmax_t std::filesystem::file_size(
    const std::filesystem::path& p, std::error_code& ec) noexcept;

std::filesystem::file_size(p) from <filesystem> behaves like reading st_size for the regular file resolved by p. For a different object type the result is implementation-defined, so do not use it as a portable directory or device measurement.

The example writes four bytes, reads their size, and then queries a missing file with the error_code overload; it prints 4 1, where the second value confirms an error.

A missing path is an error. The non-throwing file_size(p, ec) overload returns static_cast<uintmax_t>(-1) on error and sets ec; inspect ec, not only the sentinel value. The overload without ec can throw filesystem_error. The operation follows symlinks, and the result can become stale immediately after measurement.

Examples

#include <cstdint>
#include <filesystem>
#include <fstream>
#include <iostream>

int main() {
    namespace fs = std::filesystem;
    const fs::path root = fs::temp_directory_path() / "cktis-cpp-ref-file-size";
    const fs::path file = root / "data.bin";
    std::error_code ignored;
    fs::remove_all(root, ignored);
    fs::create_directory(root);
    std::ofstream(file, std::ios::binary) << "data";

    const std::uintmax_t size = fs::file_size(file);
    std::error_code ec;
    const std::uintmax_t missing = fs::file_size(root / "missing.bin", ec);
    std::cout << size << ' '
              << (missing == static_cast<std::uintmax_t>(-1) && static_cast<bool>(ec))
              << '\n';

    fs::remove_all(root, ignored);
}

Result

4 1

std::filesystem::file_size → 4 1

Sources