Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the last file name from std::filesystem::directory_iterator() without iteration?

I am trying to get the last file name. Below code does it very elegantly. But it is iterating through all the files inside the directory. Is it possible to get the last file without iteration?

#include <filesystem>
std::string latestFileName;
for (const auto &entry : fs::directory_iterator("/media/jai/Entertainment"))
      latestFileName = entry.path();
std::cout << latestFileName << std::endl;

Edited: Files in the directory is already in alphabetically increasing order. I want to pick the latest file, which is already sure to be last file in alphabetical order. As there could be million number of files, I am trying to avoid iteration.

like image 562
Jai Avatar asked Dec 10 '20 23:12

Jai


People also ask

What is Directory_iterator?

(since C++17) directory_iterator is a LegacyInputIterator that iterates over the directory_entry elements of a directory (but does not visit the subdirectories). The iteration order is unspecified, except that each directory entry is visited only once. The special pathnames dot and dot-dot are skipped.

Is regular file filesystem?

A regular file is one type of file stored in a file system. It is called "regular" primarily to distinguish it from other special types of files.


1 Answers

This isn't possible, I'm afraid, but it's also not a good idea. It's a bad idea because the order of the iteration is unspecified, and you can't guarantee that the last file is the one you want. It's not possible because std::filesystem::directory_iterator appears to be implemented internally as a singly linked list.

(via cppreference.com) The iteration order is unspecified, except that each directory entry is visited only once.

So, you gain nothing of value by accessing the last path. What is your use case? There's surely a different way to accomplish what you're trying to do.

like image 94
theOtherMichael Avatar answered Oct 19 '22 05:10

theOtherMichael