C++ 如何获取文件夹中的文件列表,其中文件按修改日期时间排序?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4283546/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get a list of files in a folder in which the files are sorted with modified date time?
提问by olidev
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.
我在 Linux 下使用 C++,支持 Boost 库。
Could anyone please provide me some sample of code of how to implement this?
任何人都可以向我提供一些如何实现这一点的代码示例吗?
回答by SingleNegationElimination
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:
大多数操作系统不会以任何特定顺序返回目录条目。如果您想对它们进行排序(如果您要将结果显示给人类用户,您可能应该这样做),您需要在单独的通道中进行。一种方法是将条目插入到 a 中std::multimap
,如下所示:
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.
然后您可以遍历result_set
,映射的boost::filesystem::path
条目将按升序排列。