Working with the File System

List Files in Directory

How do I list all files in a directory using std::filesystem?

Abstract art representing computer programming

To list all files in a directory using std::filesystem, you can use the std::filesystem::directory_iterator. This iterator allows you to iterate over the contents of a directory, providing access to each directory_entry.

Here's a simple example demonstrating how to list all files and directories in a specified path:

#include <filesystem>
#include <iostream>
namespace fs = std::filesystem;

int main() {
  fs::path dir_path{R"(c:\test)"};  
  try {
    for (const auto &entry
      : fs::directory_iterator(dir_path)) {
      std::cout << entry.path().string() << '\n';  
    }
  } catch (fs::filesystem_error &e) {
    std::cerr << e.what() << '\\n';
  }
}
c:\test\file1.txt
c:\test\file2.txt
c:\test\subdir

In this example:

  • We define dir_path as the path to the directory we want to list.
  • We use a for loop to iterate over each entry in the directory using fs::directory_iterator.
  • The entry.path() method retrieves the path of each file and directory, and we can create a std::string() from this object using the string() method.

You should include error handling because std::filesystem operations can throw exceptions, particularly if the directory does not exist or there are permission issues. The try block and catch block handle any fs::filesystem_error exceptions and print the error message.

This approach lists both files and directories. If you want to filter out directories and list only files, you can use the is_regular_file() method:

#include <filesystem>
#include <iostream>

namespace fs = std::filesystem;

int main() {
  fs::path dir_path{R"(c:\test)"};  
  try {
    for (const auto &entry
      : fs::directory_iterator(dir_path)) {
      if (fs::is_regular_file(entry.status())) {  
        std::cout << entry.path().string() << '\n';
      }
    }
  } catch (fs::filesystem_error &e) {
    std::cerr << e.what() << '\n';
  }
}
c:\test\file1.txt
c:\test\file2.txt

In this updated example, the if statement checks if the current entry is a regular file before printing its path.

Answers to questions are automatically generated and may not have been reviewed.

A computer programmer
Part of the course:

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Free, unlimited access

This course includes:

  • 124 Lessons
  • 550+ Code Samples
  • 96% Positive Reviews
  • Regularly Updated
  • Help and FAQ
Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2024 - All Rights Reserved