std::filesy...ator::depth(3)

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

okay so bestie, welcome to std::filesy...ator::depth(3) from the C++ Standard Libary manual πŸ’– β€” yes, we’re doing directory-depth math and we’re gonna make it cute.

πŸŽ€ NAME πŸŽ€

std::filesystem::recursive_directory_iterator::depth β€” that’s the whole name, bestie, and it is lowkey a mouthful. It’s the member function that tells you how deep you are in the directory tree while you’re iterating recursively. Think of it as your little depth-o-meter for recursive_directory_iterator ✨

✨ Synopsis ✨

int depth() const;  (since C++17)

So what does it do? It returns the number of directories from the starting directory to the currently iterated directory β€” i.e. the current depth of the directory hierarchy.

The starting directory has depth 0, its subdirectories have depth 1, etc. Cute, right? 🌸

⚠️ undefined behavior alert: the behavior is undefined if *this is the end iterator. Do not call depth() on an end iterator, bestie β€” that is not the vibe, and undefined behavior is never iconic πŸ’€

🌸 Parameters 🌸

  • none β€” there are literally no parameters here. zero. zilch. () energy.

πŸŽ€ Return value πŸŽ€

The current depth of the directory hierarchy. That’s the number, bestie β€” the whole point of the function πŸ’…

πŸ¦‹ Exceptions πŸ¦‹

Throws nothing. not a single exception. it’s giving calm and unbothered 🫢

πŸ‘‘ Example πŸ‘‘

This example uses iteration depth to calculate the indentation of a directory tree printout.

The original has a // Run this code marker, and here’s the code it’s pointing at:

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

int main()
{
    fs::current_path(fs::temp_directory_path());
    fs::create_directories("sandbox/a/b/c");
    fs::create_directories("sandbox/a/b/d/e");
    std::ofstream("sandbox/a/b/file1.txt");
    fs::create_symlink("a", "sandbox/syma");
    for (auto i = fs::recursive_directory_iterator("sandbox");
         i != fs::recursive_directory_iterator();
         ++i)
    {
        std::cout << std::string(i.depth() << 1, ' ') << *i;
        if (fs::is_symlink(i->symlink_status()))
            std::cout << " -> " << fs::read_symlink(*i);
        std::cout << '\n';
    }
    fs::remove_all("sandbox");
}

🌈 Output 🌈

        "sandbox/syma" -> "a"
        "sandbox/a"
          "sandbox/a/b"
            "sandbox/a/b/d"
              "sandbox/a/b/d/e"
            "sandbox/a/b/file1.txt"
            "sandbox/a/b/c"

shoutout to http://cppreference.com and the 2024.06.10 date stamp β€” that’s the source and date from the footer for std::filesy...ator::depth(3), bestie. mwah πŸ’‹

πŸ“¦ where this page comes from