Directory Iterators

Filter Directory Entries

How do I filter the directory entries to only show files?

Abstract art representing computer programming

Filtering directory entries to show only files can be achieved using a combination of std::filesystem::directory_iterator and conditional checks within the iteration loop. Here’s an example:

#include <filesystem>
#include <iostream>

namespace fs = std::filesystem;

int main() {
  fs::directory_iterator start{R"(c:\test)"};
  fs::directory_iterator end{};

  for (auto iter{start}; iter != end; ++iter) {
    if (iter->is_regular_file()) {  
      std::cout << iter->path().string() << '\n';
    }
  }
}
c:\test\file.txt
c:\test\hello.txt
c:\test\document.pdf

Steps to Filter Entries:

  1. Initialize the Iterator: Create a std::filesystem::directory_iterator pointing to the target directory.
  2. Iterate with a Condition: Within the loop, use is_regular_file() to check if the current entry is a file.
  3. Output or Process Files: If the condition is true, process the file (e.g., print its path).

Alternative Approach Using std::ranges:

You can also use std::ranges::filter() to streamline the process:

#include <filesystem>
#include <iostream>
#include <ranges>

namespace fs = std::filesystem;

int main() {
  auto entries = std::ranges::subrange{
    fs::directory_iterator{R"(c:\test)"},
    fs::directory_iterator{}};

  auto files = entries | std::views::filter(
    [](const fs::directory_entry& entry) {
      return entry.is_regular_file();
    }
  );

  for (const auto& file : files) {
    std::cout << file.path().string() << '\n';
  }
}
c:\test\file1.txt
c:\test\file2.txt
c:\test\file3.txt

This approach leverages the power of ranges to filter the entries in a more declarative manner. Both methods are effective for filtering directory entries to show only files.

This Question is from the Lesson:

Directory Iterators

An introduction to iterating through the file system, using directory iterators and recursive directory iterators

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

This Question is from the Lesson:

Directory Iterators

An introduction to iterating through the file system, using directory iterators and recursive directory iterators

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