Piyush Gadigone
Piyush Gadigone

Reputation: 31

Read newer files first from a directory - C++

Lets say I have a directory which has the files with the following names:

00 01 02 03 04 05 ...

The higher the number, the newer the file. I want to read say the 2 newest files but in descending order. So I want to read the 05 file first, then 04 file.

How can I achieve this efficiently? This directory can have 100's of files.

I know there is a readdir function in C++ but it reads the files in ascending order (First 00, then 01 and so on).

Thank you very much! :)

Upvotes: 3

Views: 1924

Answers (4)

Mr Lister
Mr Lister

Reputation: 46589

You can just use popen("ls -t", "r")

Upvotes: 1

hatboyzero
hatboyzero

Reputation: 1937

You could use boost::filesystem and std::sort to sort and then iterate through the files

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;
        }
    }
}

Upvotes: 1

alfa
alfa

Reputation: 3088

I did not check the code but this should give you an idea how it should look like. Read the file list, sort it and open the files in the correct order.

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 ...
...

Upvotes: 1

CFL_Jeff
CFL_Jeff

Reputation: 2719

Create an array of the filenames, sort the array in descending order, read the files in order of the newly sorted array.

Upvotes: 3

Related Questions