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.
std::filesystem::directory_iterator
does not sort. This boost example shows how you might copy over the paths to a vector, then sort it withstd::sort()
. – Superfamily