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?
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With