Development

Get List of Files in Directory in C++

Captain Salem 3 min read

Get a List of Files in the Directory in C++

Getting a list of files in a given directory is some of the most common and basic computer usage tasks. As a developer, it is, therefore, reasonable to understand how file listing in a directory works.

In this tutorial, we cover some methods of implementing a program that lists the files and directories of a given directory using C++.

Using the filesystem::directory_iterator

In C++ 17 and above, we have access to the directory_iteratormethod from the filesystem package. As the name suggests, this method performs an iteration, going through each item in a given directory one after another.

The method takes the path to the target directory as the argument. We can use the method as the argument for` a loop to iterate over each file and directory in the target path.

Example code:

//
//  main.cpp
//  GeekBits
//
//  Created by captain on 01/12/2022.
//

#include <iostream>
#include <filesystem>
#include <string>
#include <vector>

using std::cin; using std::cout;
using std::filesystem::directory_iterator;
using std::endl; using std::string;


int main(int argc, const char * argv[]) {
    string directory_path = "/Users/csalem/Desktop";
    for (const auto & file: directory_iterator(directory_path)) {
        cout << file.path() << endl;
    }
    return 0;
}

Once we run the code above, we should get the path of the files and directories in the target path. An example output is as shown:

"/Users/csalem/Desktop/Developer"
"/Users/csalem/Desktop/.DS_Store"
"/Users/csalem/Desktop/.localized"
"/Users/csalem/Desktop/articles"
"/Users/csalem/Desktop/GeekBits"
"/Users/csalem/Desktop/codes"
"/Users/csalem/Desktop/temp_files"
Program ended with exit code: 0

Note that the output may vary depending on your target directory.

Using the std::filesystem::recursive_directory_iterator

We can also use the recursive_directory_iterator method to fetch the list of files and directories. This method behaves similarly to the directory_iterator. However, it is useful when working with subdirectories where you need to search for specific filenames.

Example code:

//
//  main.cpp
//  GeekBits
//
//  Created by captain on 01/12/2022.
//

#include <iostream>
#include <filesystem>
#include <string>
#include <vector>

using std::cin; using std::cout;
using std::filesystem::recursive_directory_iterator;
using std::endl; using std::string;


int main(int argc, const char * argv[]) {
    string directory_path = "/Users/csalem/Desktop";
    for (const auto & file: recursive_directory_iterator(directory_path)) {
        cout << file.path() << endl;
    }
    return 0;
}

Running the code above should allow the program to list all the files and directories even in multiple subdirectories as:

"/Users/csalem/Desktop/Developer"
"/Users/csalem/Desktop/Developer/test_variable.sh"
"/Users/csalem/Desktop/Developer/passkeep.py"
"/Users/csalem/Desktop/Developer/test.py"
"/Users/csalem/Desktop/Developer/sender.java"
"/Users/csalem/Desktop/Developer/nanproduct.py"
"/Users/csalem/Desktop/Developer/fs.cpp"
"/Users/csalem/Desktop/Developer/main.py"
"/Users/csalem/Desktop/.DS_Store"
"/Users/csalem/Desktop/.localized"
"/Users/csalem/Desktop/GeekBits"
"/Users/csalem/Desktop/GeekBits/.DS_Store"
"/Users/csalem/Desktop/GeekBits/GeekBits.xcodeproj"
"/Users/csalem/Desktop/GeekBits/GeekBits.xcodeproj/project.pbxproj"
"/Users/csalem/Desktop/GeekBits/GeekBits.xcodeproj/xcuserdata"
"/Users/csalem/Desktop/GeekBits/GeekBits.xcodeproj/xcuserdata/csalem.xcuserdatad"
"/Users/csalem/Desktop/GeekBits/GeekBits.xcodeproj/xcuserdata/csalem.xcuserdatad/xcschemes"
"/Users/csalem/Desktop/GeekBits/GeekBits.xcodeproj/xcuserdata/csalem.xcuserdatad/xcschemes/xcschememanagement.plist"
"/Users/csalem/Desktop/GeekBits/GeekBits.xcodeproj/project.xcworkspace"
"/Users/csalem/Desktop/GeekBits/GeekBits.xcodeproj/project.xcworkspace/contents.xcworkspacedata"
"/Users/csalem/Desktop/GeekBits/GeekBits.xcodeproj/project.xcworkspace/xcuserdata"
"/Users/csalem/Desktop/GeekBits/GeekBits.xcodeproj/project.xcworkspace/xcuserdata/csalem.xcuserdatad"
"/Users/csalem/Desktop/GeekBits/GeekBits.xcodeproj/project.xcworkspace/xcuserdata/csalem.xcuserdatad/UserInterfaceState.xcuserstate"
"/Users/csalem/Desktop/GeekBits/GeekBits.xcodeproj/project.xcworkspace/xcshareddata"
"/Users/csalem/Desktop/GeekBits/GeekBits.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist"
"/Users/csalem/Desktop/GeekBits/GeekBits.xcodeproj/project.xcworkspace/xcshareddata/swiftpm"
"/Users/csalem/Desktop/GeekBits/GeekBits.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/configuration"
"/Users/csalem/Desktop/GeekBits/GeekBits"
"/Users/csalem/Desktop/GeekBits/GeekBits/main.cpp"
"/Users/csalem/Desktop/codes"
"/Users/csalem/Desktop/codes/geekbits.http"
"/Users/csalem/Desktop/codes/string_conversion.java"
"/Users/csalem/Desktop/codes/byte_array_to_string.go"
"/Users/csalem/Desktop/codes/table.cql"

Using the opendir/readdir Functions

We can also use the opendir and readdir functions from the direct.h header file to read files in a given directory. As the name suggests, the opendir opens the directory at the specified path and returns a DIR* pointer, while the readdir method operates the DIR* pointer and returns the pointer and returns a structure that represents the next directory entry in the directory stream.

You can learn more here -> https://www.man7.org/linux/man-pages/man3/readdir.3.html

We can put the readdirfunction on a while loop and compare the nullptr which works as directory iterator. We can then fetch the filenames from the struct of the function.

Example:

//
//  main.cpp
//  GeekBits
//
//  Created by captain on 01/12/2022.
//

#include <iostream>
#include <vector>
#include <dirent.h>

using std::cin; using std::cout; using std::endl;
using std::vector;

int main(int argc, const char * argv[]) {
    DIR *dir_ptr;
    struct dirent *diread;
    vector<char *> filenames;
    if ((dir_ptr = opendir("/Users/csalem/Desktop")) != nullptr) {
        while ((diread = readdir(dir_ptr)) != nullptr) {
            filenames.push_back(diread->d_name);
        }
        closedir(dir_ptr);
    } else {
        perror("fail");
        return -1;
    }
    for (auto file: filenames) {
        cout << file << "";
        cout << endl;
    }
    return 0;
}

Output:

.
..
Developer
.DS_Store
.localized
articles
GeekBits
codes
temp_files
Program ended with exit code: 0

Conclusion

In this tutorial, you discovered three main methods for fetching files and listing a given directory in C++.

Share
Comments
More from Cloudenv

Cloudenv

Developer Tips, Tricks and Tutorials.

Great! You’ve successfully signed up.

Welcome back! You've successfully signed in.

You've successfully subscribed to Cloudenv.

Success! Check your email for magic link to sign-in.

Success! Your billing info has been updated.

Your billing was not updated.