How to get a list of files in a folder in which the files are sorted with modified date time?

前端 未结 1 1929
梦如初夏
梦如初夏 2020-12-05 03:01

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.

相关标签:
1条回答
  • 2020-12-05 03:25

    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.

    0 讨论(0)
提交回复
热议问题