std::filesy...entry::path(3)

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

✨ std::filesystem::directory_entry::path ✨

okay bestie, so this is a page straight out of the C++ Standard Libary (their spelling, not mine πŸ’…) β€” it's std::filesystem::directory_entry::path, and honestly it's giving "small but mighty."

🌸 NAME 🌸

std::filesystem::directory_entry::path β€” yes, the name is the whole thing twice, that's just how the standard library does it, periodt.

πŸŽ€ Synopsis πŸŽ€

const std::filesystem::path& path() const noexcept;       (since C++17)
operator const std::filesystem::path& () const noexcept;  (since C++17)

So you get two ways in β€” the named path() getter and the conversion operator β€” both noexcept, both const, both since C++17. Two icons, same energy fr fr. πŸ’–

What does it do? It returns the full path the directory entry refers to. That's the whole vibe check.

πŸ¦‹ Parameters πŸ¦‹

(none) β€” literally none, it takes zero arguments, it's low-maintenance like that πŸ™ˆ

⭐ Return value ⭐

The full path the directory entry refers to. Exactly what it says on the tin, no plot twist. 🫢

πŸ”₯ Example πŸ”₯

Run this code
#include <filesystem>
#include <fstream>
#include <iostream>

namespace fs = std::filesystem;

std::string get_stem(const fs::path& p) { return p.stem().string(); }
void create_file(const fs::path& p) { std::ofstream o{p}; }

int main()
{
    const fs::path dir{"tmp_dir"};
    fs::create_directory(dir);
    create_file(dir / "one");
    create_file(dir / "two");
    create_file(dir / "three");

    for (const auto& file : fs::directory_iterator(dir))
    {
        // Explicit conversion
        std::cout << get_stem(file.path()) << '\n';

        // Implicit conversion
        std::cout << get_stem(file) << '\n';
    }

    fs::remove_all(dir);
}

Bestie look at this β€” they call get_stem(file.path()) (explicit conversion) and then just get_stem(file) (implicit conversion), and both work because of that operator const std::filesystem::path&. That's the moment. 🫒✨

πŸ’œ Possible output πŸ’œ

two
two
one
one
three
three

(note the "possible" β€” it's a directory iterator, the order is not the point, the doubling is the point πŸ‘‘)

🌈 See also 🌈

  • path β€” represents a path (C++17) (class)

okay that's the tea πŸ“ β€” this page came from http://cppreference.com, dated 2024.06.10, and you can find it filed under std::filesy...entry::path(3) in the C++ Standard Libary, mwah πŸ’…πŸ§šπŸ’–

πŸ“¦ where this page comes from