How to sort a ReadDir iterator

I can display the list of directories as follows:

use std::fs; fn main() { let paths = fs::read_dir("./").unwrap(); for path in paths { println!("Name: {}", path.unwrap().path().display()) } } 

Is it possible to sort the ReadDir iterator before iteration? Directory names are numbers with a date, such as 201610131503 . I read the documentation for ReadDir , but for this I did not find a built-in function. Maybe I do not know how to search?

+8
iterator rust
source share
2 answers

ReadDir reads only one record at a time, so it cannot sort it before iterating. There is no sorted ReadDir system call (at least on those platforms that I know of, which means portable can't be).

So, the only option is to read Vec and sort it:

 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()) } } 
+6
source share

Is it possible to sort the ReadDir iterator before iteration?

In principle, no. On macOS and Linux, the readdir_r function is readdir_r . This does not guarantee a return in any particular order . As a rule, it returns in the order that is the fastest / easiest for the file system, which can change every time you call it.

You will need to collect the elements, sort them, and then repeat the iteration.

+4
source share

All Articles