Jyegda
Jyegda

Reputation: 13

How to find the most recent file in a directory using cpp filesystem

I'm trying to get the most recent file in a log directory. I'm using c++ and filesystem library.

I tried to use a directory_iterator from experimental/filesystem to iterate on every file in my directory, and, using std::max_element, compare the last_write_time of each file to have the greater one.

namespace fs = std::experimental::filesystem;
auto dir_it = fs::directory_iterator(my_path);
auto path = *std::max_element(fs::begin(dir_it), fs::end(dir_it), [](const fs::directory_entry& f1, const fs::directory_entry& f2){
  return fs::last_write_time(f1.path()) < fs::last_write_time(f2.path());
});

I expect to get an fs::directory_entry object but when I print the path, it's empty. So I took a look at the compared elements inside my function, and at each step, f1.path() == f2.path(), so the output is understandable but I didn't figure out why the compare function doesn't work.

Upvotes: 1

Views: 1282

Answers (1)

Nicol Bolas
Nicol Bolas

Reputation: 473926

max_element requires a forward iterator, while directory_iterator is an input iterator.

So if you want to do things this way, you'll need to either create a container from the iterators, or manually write a loop yourself.

Upvotes: 2

Related Questions