Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
443 views
in Technique[技术] by (71.8m points)

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...