CodingHowTo

Filesystem 101: List Files in a Directory (std::filesystem)

Filesystem 101: List Files in a Directory (std::filesystem)

Content

        #include <iostream>
        #include <filesystem>

        namespace fs = std::filesystem;

        int main() {
            fs::path dirPath = "your/directory/path";

            try {
                for (const auto& entry : fs::directory_iterator(dirPath)) {
                    std::cout << entry.path() << '\n';
                }
            } catch (const fs::filesystem_error& e) {
                std::cerr << "Error: " << e.what() << '\n';
            }

            return 0;
        }
    

The code above demonstrates how to use std::filesystem to iterate through all entries in a specified directory and print their paths. We start by including the necessary headers, then define the path of the directory we want to list files from. Using a try-catch block, we handle any potential filesystem errors that might occur during the iteration.

Conclusion

Using C++17's std::filesystem library makes it straightforward to list files in a directory. By following this simple guide, you can efficiently navigate and manipulate the filesystem within your C++ applications. This functionality is particularly useful for tasks such as file management, backups, or any application that requires interaction with the operating system's file structure.