In this article we will discuss how to fetch the recursive list of all files in a given directory using Boost and C++17 FileSystem Library.

Suppose we have a directory i.e.

/home/user/study/tutorials

and I want list of all files in this directory and its sub directories, but also want to skip certain directory like .svn and log etc.

Let’s see how to do that,

recursive_directory_iterator

Both Boost & c++17 Filesystem Library provides a recursive iterator for the recursive iteration over a directory i.e.

In C++17

In Boost Filesystem Library,

It’s an input iterator and using it we can recursively iterate over a directory and all its sub directories.

Create a recursive_directory_iterator object and points to start of directory i.e.

Create a recursive_directory_iterator object and points to end.

Now Iterate over all the directories and sub directories by incrementing the iterator till end i.e.

In between, if we dont’t want the iterator over certain sub directories, then we need to call,

and

with iterator pointing to that directory. Calling this function will disable the recursive iteration of current function

Checkout the complete function as follows,

For Boost FileSystem Library, we need to include following file and create following namespace i.e.

For C++17 FileSystem Library, we need to include following file and create following namespace i.e.

Complete example with Boost header file is as follows,

To compile the above example use following command on linux,

g++ -std=c++11 example.cpp -lboost_filesystem -lboost_system

Sample example can be compiled with c++17 file system after replacing header file and namespace as mentioned above. To compile it in c++17, use following command,

g++-7 –std=c++17 example.cpp -lstdc++fs

Click Here to Subscribe for more Articles / Tutorials like this.