I can display a directory list like this:
use std::fs;
fn main() {
let paths = fs::read_dir("./").unwrap();
for path in paths {
println!("Name: {}", path.unwrap().path().display())
}
}
Can I sort the ReadDir
iterator before iteration? The directory names are date-like numbers like 201610131503
. I read the documentation for ReadDir
but I did not find a built-in function for this. Maybe I do not know how to search?
Can I sort the ReadDir iterator before iteration? Basically, no. On macOS and Linux, the readdir_r function is used. This is not guaranteed to return in any specific order. Generally, it will return in the order that is fastest / easiest for the filesystem, which could change every time you call it.
The filenames returned by readdir() are not in sorted order, but rather in the order in which they happen to occur in the directory (this depends on the order in which the file system adds files to the directory and how it fills gaps in the directory list after files are removed).
Returns an iterator over the entries within a directory. The iterator will yield instances of io::Result < DirEntry > . New errors may be encountered after an iterator is initially constructed. Entries for the current and parent directories (typically . and ..) are skipped.
SortedSet iterator () method in Java with Examples Last Updated : 30 Sep, 2019 The java.util.SortedSet.iterator () method is used to return an iterator of the same elements as the set. The elements are returned in random order from what present in the set.
ReadDir
only reads one entry at a time, so it can't sort it before iterating. There is no sorted readdir
system call (at least not on the platforms I know of, which means there can't be a portable one).
So the only option is to read into a Vec
and sort there:
use std::fs;
fn main() {
let mut paths: Vec<_> = fs::read_dir("/").unwrap()
.map(|r| r.unwrap())
.collect();
paths.sort_by_key(|dir| dir.path());
for path in paths {
println!("Name: {}", path.path().display())
}
}
Can I sort the
ReadDir
iterator before iteration?
Basically, no. On macOS and Linux, the readdir_r
function is used. This is not guaranteed to return in any specific order. Generally, it will return in the order that is fastest / easiest for the filesystem, which could change every time you call it.
You will need to collect the items, sort them, then re-iterate.
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