Walking directories with directory_iterator
A fs::directory_iterator
is just what it says on the tin. An object of this type lets you walk the contents of a single directory, entry by entry:
fs::path p = fs::current_path(); // List the current directory. for (fs::directory_entry entry : fs::directory_iterator(p)) { std::cout << entry.path().string() << ": " << entry.file_size() << " bytes\n"; }
Incidentally, notice the use of entry.path().string()
in the preceding code. This is required, because operator<<
acts extremely bizarrely on path objects--it always outputs as if you'd written std::quoted(path.string())
. If you want the path itself, with no extra quotes, you always have to convert to std::string
before outputting. (Similarly, std::cin >> path
won't work to get a path from the user, but that's less obnoxious, since you should never use operator>>
anyway. See Chapters 9, Iostreams, and Chapter 10, Regular Expressions...