List files in a directory
The filesystem
library provides a directory_entry
class with directory-related information about a given path
. We can use this to create useful directory listings.
How to do it…
In this recipe, we create a directory listing utility using the information in the directory_entry
class:
- We start with our namespace alias and
formatter
specialization for displayingpath
objects:namespace fs = std::filesystem; template<> struct std::formatter<fs::path>: std::formatter<std::string> { template<typename FormatContext> auto format(const fs::path& p, FormatContext& ctx) { return format_to(ctx.out(), "{}", p.string()); } };
- The
directory_iterator
class makes it easy to list a directory:int main() { constexpr const char* fn{ "." }; ...