C++ get all files in directory – C++ Program to Get the List of all Files in a Given Directory and its Sub-Directories

C++ get all files in directory: In the previous article, we have discussed C++ Program to Check Whether a Character is an Alphabet or Not. In this article, we will see C++ Program to Get the List of all Files in a Given Directory and its Sub-Directories.

Method to get the list of all files in a given directory and its sub-directories

C++ get list of files in directory: In this article, we discuss how can we get the list of all files in a given directory and its sub-directories. The method that we discuss is given below:

Let’s first understand what we actually going to do in this article. Suppose there is a path p=”dir/file1/file2″. So we have to list all the files in this path. In a path, there may be multiple directories and in these directories, there may be multiple files. So we have to return or print the list of all the files. So now let’s discuss the method.

Method 1:-Using recursive_directory_iterator

C++ list files in directory: First, we discuss what a recursive_directory_iterator is. C++17 Filesystem Library provides a recursive iterator for the recursive iteration over a directory. recursive_directory_iterator is a LegacyInputIterator that iterates over the directory_entry elements of a directory, and, recursively, over the entries of all subdirectories. The iteration order is unspecified, except that each directory entry is visited only once. Now let’s write the code of how to use recursive_directory_iterator to get the list of all files in a given directory and its sub-directories.

#include <fstream>
#include <iostream>
#include <filesystem>
namespace fs = std::filesystem;
 
int main()
{
    fs::current_path(fs::temp_directory_path());
    fs::create_directories("dir/file1/file2");
    std::ofstream("dir/file1.txt");
    fs::create_symlink("file1", "dir/file2");
    for(auto& p: fs::recursive_directory_iterator("dir"))
        std::cout << p.path() << '\n';
    fs::remove_all("dir");
}

Output

"dir/file2"
"dir/file1.txt"
"dir/file1"
"dir/file1/file2"

So here we see we get the list of all the files in the directory and sub_directories.

So this is the method to get the list of all the files in the directory and sub_directories in c++.

The popular Examples of C++ Code are programs to print Hello World or Welcome Note, addition of numbers, finding prime number and so on. Get the coding logic and ways to write and execute those programs.