BIOStheZerg
BIOStheZerg

Reputation: 446

Can the order of files be changed when iterating a directory using boost::filesystem?

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?

Upvotes: 1

Views: 1654

Answers (1)

Maxim Egorushkin
Maxim Egorushkin

Reputation: 136306

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';

Upvotes: 4

Related Questions