首先从目录中读取较新的文件 - C ++

时间:2012-03-02 20:23:35

标签: c++

假设我有一个目录,其中包含以下名称的文件:

00 01 02 03 04 05 ...

数字越大,文件越新。我想阅读说2个最新的文件,但按降序排列。所以我想首先阅读05文件,然后阅读04文件。

如何有效地实现这一目标?这个目录可以有100个文件。

我知道C ++中有一个readdir函数,但它按升序读取文件(第一个00,然后是01,依此类推)。

非常感谢! :)

4 个答案:

答案 0 :(得分:3)

创建一个文件名数组,按降序对数组进行排序,按照新排序的数组的顺序读取文件。

答案 1 :(得分:1)

您可以使用boost::filesystemstd::sort进行排序,然后遍历文件

struct comparator {
    bool operator()(boost::filesystem::path i, 
                    boost::filesystem::path j)
    { 
        return (i>j);
    }

} myComparator;

...

boost::filesystem::path folderPath = "/path/to/some/folder";

if (boost::filesystem::exists(folderPath))
{
    if (boost::filesystem::is_directory(folderPath))
    {
        typedef std::vector<boost::filesystem::path> vec;
        vec v;

        std::copy(
            boost::filesystem::directory_iterator(folderPath),
            boost::filesystem::directory_iterator(),
            std::back_inserter(v)
        );

        std::sort(v.begin(), v.end(), myComparator);

        for (vec::const_iterator it(v.begin()); it != v.end; ++it)
        {
            std::cout << "File: " << *it << std::endl;
        }
    }
}

答案 2 :(得分:1)

我没有检查代码,但这应该让你知道它应该是什么样子。阅读文件列表,对其进行排序并按正确的顺序打开文件。

DIR dir;
struct dirent *dir_entry;
dir = opendir("dir/path")

std::vector<std::string> file_list;
file_list.reserve(N);
while(dir=readdir(dir))
{
  if (dir_entry->d_type == DT_REG)
  {
    file_list.push_back(std::string(dir_entry->d_name));
  }
}
std::sort(file_list.begin(), file_list.end());
// open files ...
...

答案 3 :(得分:1)

您可以使用popen("ls -t", "r")