std::filesy...ator::depth(3)
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*thisis the end iterator. Do not calldepth()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
- nixpkgs unstable: stdman 2024.07.05
- opensuse-leap 16.0: stdman 2024.07.05-bp160.1.9 Β· MIT
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash-1017 on : a language model's rewrite of the original, under its terms