std::experi...::file_size(3)

πŸ“¦ version 2024.07.05, in nixpkgs unstable, opensuse-leap 16.0

πŸ’– NAME πŸ’–

okay bestie, this is the C++ Standard Libary manual page for std::experi...::file_size(3) ✨. The NAME line is literally std::experimental::filesystem::file_size β€” std::experimental::filesystem::file_size (yes, the same name on both sides, she said what she said πŸ’…).


✨ Synopsis ✨

Defined in header <experimental/filesystem> πŸ¦‹

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

okay so file_size returns the size of the regular file p, determined as if by reading the st_size member of the structure obtained by POSIX stat (symlinks are followed). 🫢

Attempting to determine the size of a directory (as well as any other file that is not a regular file or a symlink) is treated as an error.

The non-throwing overload returns returns -1 on errors.


πŸŽ€ Parameters πŸŽ€

  • p β€” path to examine πŸ”
  • ec β€” out-parameter for error reporting in the non-throwing overload 🧚

🌸 Return value 🌸

The size of the file, in bytes. that’s the whole answer, periodt. πŸ’–


πŸ’€ Exceptions πŸ’€

The overload that does not take an error_code& parameter throws filesystem_error on underlying OS API errors, constructed with p as the first argument and the OS error code as the error code argument. std::bad_alloc may be thrown if memory allocation fails.

The overload taking an error_code& parameter sets it to the OS API error code if an OS API call fails, and executes ec.clear() if no errors occur. This overload has noexcept specification: noexcept. 😌


πŸ“ Example πŸ“

// Run this code

#include <experimental/filesystem>
#include <fstream>
#include <iostream>
namespace fs = std::experimental::filesystem;

int main()
{
    fs::path p = fs::current_path() / "example.bin";
    std::ofstream(p).put('a'); // create file of size 1
    std::cout << "File size = " << fs::file_size(p) << '\n';
    fs::remove(p);

    try
    {
        fs::file_size("/dev"); // attempt to get size of a directory
    }
    catch (fs::filesystem_error& e)
    {
        std::cout << e.what() << '\n';
    }
}

Possible output: πŸ‘€

File size = 1
filesystem error: cannot get file size: Is a directory [/dev]

πŸ’œ See also πŸ’œ

  • resize_file β€” changes the size of a regular file by truncation or zero-fill (function). πŸͺ„
  • space β€” determines available free space on the file system (function). 🌈

πŸ‘‘ Categories πŸ‘‘

  • Noindexed pages
  • unconditionally noexcept

πŸ™ˆ Hidden categories πŸ™ˆ

  • Pages with unreviewed unconditional noexcept template
  • Pages with unreviewed noexcept template

Source/version/date sign-off bestie: this page is from http://cppreference.com, version/date 2024.06.10, and the page title is std::experi...::file_size(3) β€” mwah πŸ’‹πŸ«Ά

πŸ“¦ where this page comes from