Chapter 13. Reading directory contents

Index

Reading the contents of a single directory
Reading the contents of a directory hierarchy
Miscellaneous functions

Several classes provide iterators that return contents of directories. x::dir (as well as the customary x::dirptr and, in this case, x::const_dir and x::const_dirptr) is a reference to a reference-counted object that represents a directory with iteratable contents. It uses x::dir::base::iterator to iterate over the contents of a single directory. x::dirwalk/x::dirwalkptr and x::dirwalk::base::iterator open and recursively walk through an entire directory tree.

Reading the contents of a single directory

#include <x/dir.H>

x::dir etcdir=x::dir::create("/etc", true);
x::dir::base::iterator etcdirb(etcdir->begin()), etcdire(etcdir->end());

while (etcdirb != etcdire)
{
    std::cout << (std::string)*etcdirb << std::endl;
    ++etcdirb;
}

// Or, a short version:

auto etcdir=x::dir::create("/etc", true);
for (auto direntry: *etcdir)
{
    std::cout << (std::string)direntry << std::endl;
}

x::dir is just a factory for beginning and ending iterators, Its begin() and end() return x::dir::base::iterators that define an input sequence that iterate over the contents of a directory. Dereferencing a non-ending iterator returns a x::dir::base::entry which can be casted to a std::string, giving the file's name.

x::dir::base::entry also has the following methods:

fullpath()

The full path of the directory entry. This is the directory name given to x::dir's constructor followed by the name of the directory entry.

filetype()

The type of the directory entry. Most Linux filesystems return the type of a directory entry together with its name, so it is readily available. On other filesystems, filetype() issues an explicit lstat(2) call. DT_UNKNOWN gets returned if lstat(2) fails.