The Directory Entry & Directory Iteration

In this lesson, we'll see different ways of iterating over a path.

While the path class represent files or paths that exist or not, we also have another object that is more concrete: it’s directory_entry object. This object points to existing files and directories, and it’s usually obtained by iterating using filesystem iterators.

What’s more, implementations are encouraged to cache the additional file attributes. That way there can be fewer system calls.

Traversing a Path with Directory Iterators

You can traverse a path using two available iterators:

  • directory_iterator - iterates in a single directory, input iterator
  • recursive_directory_iterator - iterates recursively, input iterator

In both approaches the order of the visited filenames is unspecified, each directory entry is visited only once.

If a file or a directory is deleted or added to the directory tree after the directory iterator has been created, it is unspecified whether the change would be observed through the iterator.

In both iterators the directories . and .. are skipped.

You can iterate through a directory using the following pattern:

Get hands-on with 1200+ tech skills courses.