28

I need to a list of files in a folder and the files are sorted with their modified date time.

I am working with C++ under Linux, the Boost library is supported.

Could anyone please provide me some sample of code of how to implement this?

halfer
  • 19,824
  • 17
  • 99
  • 186
olidev
  • 20,058
  • 51
  • 133
  • 197
  • 2
    How does this differ from your other question: http://stackoverflow.com/questions/4279164/cboost-file-system-to-return-a-list-of-files-older-than-a-specific-time? Nabulke has provided you with an answer that should point you in the right direction. From there it's not too hard to add the files to a vector and to sort them. – Ralf Nov 26 '10 at 08:42
  • Possible duplicate of [C++:boost file system to return a list of files older than a specific time](https://stackoverflow.com/questions/4279164/cboost-file-system-to-return-a-list-of-files-older-than-a-specific-time) – halfer Feb 16 '18 at 14:25

1 Answers1

55

Most operating systems do not return directory entries in any particular order. If you want to sort them (you probably should if you are going to show the results to a human user), you need to do that in a separate pass. One way you could do that is to insert the entries into a std::multimap, something like so:

namespace fs = boost::filesystem;
fs::path someDir("/path/to/somewhere");
fs::directory_iterator end_iter;

typedef std::multimap<std::time_t, fs::path> result_set_t;
result_set_t result_set;

if ( fs::exists(someDir) && fs::is_directory(someDir))
{
  for( fs::directory_iterator dir_iter(someDir) ; dir_iter != end_iter ; ++dir_iter)
  {
    if (fs::is_regular_file(dir_iter->status()) )
    {
      result_set.insert(result_set_t::value_type(fs::last_write_time(dir_iter->path()), *dir_iter));
    }
  }
}

You can then iterate through result_set, and the mapped boost::filesystem::path entries will be in ascending order.

halfer
  • 19,824
  • 17
  • 99
  • 186
SingleNegationElimination
  • 151,563
  • 33
  • 264
  • 304
  • 1
    just a note here that if files are created/modified within the same second, their order is not guaranteed, as `std::time_t` is accurate to the second. – fduff Oct 18 '13 at 09:33
  • 2
    Please note http://www.boost.org/doc/libs/1_46_1/libs/filesystem/v3/doc/reference.html#last_write_time. last_write_time gets path not status. fs::last_write_time(dir_iter->path()) – e271p314 Feb 17 '14 at 08:33
  • 1
    Can I sort the vector of paths in the last_write_time manner? – sop Dec 03 '14 at 16:52
  • 3
    C++11 version with auto and make_iterator_range: http://stackoverflow.com/a/20925615/472308 –  Oct 27 '15 at 14:34
  • C++17 introduced std::filesystem::last_write_time. You probably don't need boost to compile the example provided. – kindrobot May 18 '22 at 18:05