15

I have used boost::filesystem::directory_iterator in order to get a list of all the available files into a given folder.

The problem is that I supposed this method would give me the files in alphabetical order, while the results seem pretty random.

Is there any fancy way of alphabetically sorting them?

My current code:

if(boost::filesystem::is_directory(myFolder)){
    // Iterate existing files
    boost::filesystem::directory_iterator end_iter;
    for(boost::filesystem::directory_iterator dir_itr(myFolder);
        dir_itr!=end_iter; dir_itr++){

        boost::filesystem::path filePath;
        // Check if it is a file
        if(boost::filesystem::is_regular_file(dir_itr->status())){
            std::cout << "Reading file " << dir_itr->path().string() << std::cout;
        }
    }
}
sehe
  • 374,641
  • 47
  • 450
  • 633
Roman Rdgz
  • 12,836
  • 41
  • 131
  • 207
  • 3
    not very fancy but it should work: put them in a vector and sort the vector. – 463035818_is_not_an_ai Jun 22 '15 at 14:56
  • 1
    The problem becomes worse when you need to sort them in a more complex way. For example: if you need to sort them based on some information in file headers you will have to open files one by one -> read header -> close file. Then, sort the files. Finally you will have to start another loop opening each file to read data records – Ahmed Hussein Dec 26 '18 at 12:53

2 Answers2

26

The fanciest way I've seen to perform what you want is straight from the boost filesystem tutorial. In this particular example, the author appends the filename/directory to the vector and then utilizes a std::sort to ensure the data is in alphabetical order. Your code can easily be updated to use this same type of algorithm.

Tyler Jandreau
  • 4,245
  • 1
  • 22
  • 47
8

straight from the boost filesystem tutorial.

Thank you Tyler for the link.

If you are lazy, here is the adapted code:

std::vector<std::filesystem::path> files_in_directory;
std::copy(std::filesystem::directory_iterator(myFolder), std::filesystem::directory_iterator(), std::back_inserter(files_in_directory));
std::sort(files_in_directory.begin(), files_in_directory.end());

for (const std::string& filename : files_in_directory) {
    std::cout << filename << std::endl; // printed in alphabetical order
}
ldg
  • 450
  • 3
  • 7
  • 27
PJ127
  • 986
  • 13
  • 23