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.
(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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With