std::filesy..._link_count(3)

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

🌸 NAME 🌸

Okay bestie, welcome to the std::filesy..._link_count(3) page from the C++ Standard Libary (yes, that's how the header spells it, and we are not editing the header πŸ’…). The NAME is std::filesystem::hard_link_count β€” std::filesystem::hard_link_count. It's giving iconic repetition, periodt ✨.


✨ Synopsis ✨

Defined in header <filesystem> πŸŽ€

std::uintmax_t hard_link_count( const std::filesystem::path& p ); (1)
std::uintmax_t hard_link_count( const std::filesystem::path& p,
                                std::error_code& ec ) noexcept; (2)

Both overloads are (since C++17) πŸ’–.

So what does it do? It returns the number of hard links for the filesystem object identified by path p. Literally that's the whole vibe πŸ¦‹.

And the non-throwing overload? On errors it returns static_cast<uintmax_t>(-1) β€” yes, that exact cast, bestie 😭.


πŸŽ€ Parameters πŸŽ€

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

πŸ’– Return value πŸ’–

The number of hard links for p. That's it, that's the return value, no cap ✨.


😭 Exceptions 😭

Any overload not marked noexcept may throw std::bad_alloc if memory allocation fails. Like, allocation said nope πŸ’€.

  1. Throws std::filesystem::filesystem_error on underlying OS API errors, constructed with p as the first path argument and the OS error code as the error code argument.
  2. Sets a std::error_code& parameter to the OS API error code if an OS API call fails, and executes ec.clear() if no errors occur.

πŸ¦‹ Example πŸ¦‹

// Run this code

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

int main()
{
    // On a POSIX-style filesystem, each directory has at least 2 hard links:
    // itself and the special member pathname "."
    fs::path p = fs::current_path();
    std::cout << "Number of hard links for current path is "
              << fs::hard_link_count(p) << '\n';

    // Each ".." is a hard link to the parent directory, so the total number
    // of hard links for any directory is 2 plus number of direct subdirectories
    p = fs::current_path() / ".."; // Each dot-dot is a hard link to parent
    std::cout << "Number of hard links for .. is "
              << fs::hard_link_count(p) << '\n';
}

🌈 Possible output 🌈

Number of hard links for current path is 2
Number of hard links for .. is 3

πŸ‘‘ See also πŸ‘‘

  • create_hard_link β€” creates a hard link. (C++17) (function)
  • hard_link_count β€” returns the number of hard links referring to the file to which the directory entry refers. (public member function of std::filesystem::directory_entry)

And that's the page, bestie 🫢. Cute sign-off time: source/date is http://cppreference.com and 2024.06.10, under the std::filesy..._link_count(3) banner. Byeee, go count some links πŸ’…βœ¨

πŸ“¦ where this page comes from