1

I have inherited some code using boost's directory_iterator:

for (directory_iterator fileIt{currDir}; fileIt != directory_iterator{}; ++fileIt) {
  // Do stuff with files
}

and I would like to process the files in a particular order (simple alphabetical sorting would do). Is there any way to achieve this, i.e. to enforce the iterator to give me files according to some sorting instead of the default?

BIOStheZerg
  • 396
  • 4
  • 19

1 Answers1

4

You need to sort it yourself because the order of directory entries obtained by dereferencing successive increments of a directory_iterator is unspecified:

std::vector<boost::filesystem::path> paths(
      boost::filesystem::directory_iterator{"."}
    , boost::filesystem::directory_iterator{}
    );
std::sort(paths.begin(), paths.end());
for(auto const& path : paths)
    std::cout << path << '\n';
Maxim Egorushkin
  • 131,725
  • 17
  • 180
  • 271
  • 1
    May be worth mentioning that [filesystems do not generally handle well directories with more than 10000 files or so](https://stackoverflow.com/a/466596/412080). So that loading all filenames from a directory into a vector should not be a concern, because something else would probably break first. – Maxim Egorushkin Feb 14 '18 at 23:42
  • https://www.boost.org/doc/libs/1_71_0/libs/filesystem/doc/tutorial.html#Using-path-decomposition – kervin Oct 29 '19 at 17:40