Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

boost

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?

like image 438
olidev Avatar asked Nov 26 '10 08:11

olidev


People also ask

What command allows you to list files sorted by when they were last modified?

The 'ls' command lists all files and folders in a directory at the command line, but by default ls returns a list in alphabetical order. With a simple command flag, you can have ls sort by date instead, showing the most recently modified items at the top of the ls command results.

Which command is used to obtain a list of all files by modification time?

ls command ls – Listing contents of directory, this utility can list the files and directories and can even list all the status information about them including: date and time of modification or access, permissions, size, owner, group etc.

How do you get a directory listing sorted by creation date in Python?

To get a directory listing sorted by creation date in Python, you can call os. listdir() to get a list of the filenames. Then call os. stat() for each one to get the creation time and finally sort against the creation time.


1 Answers

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.

like image 105
SingleNegationElimination Avatar answered Oct 13 '22 17:10

SingleNegationElimination