std-function

fs::read_dir: enumerate directory entries

Iterate directory entries with per-entry errors. Enumeration order is not guaranteed; sort names for deterministic presentation. Run only inside a disposable working directory. The fixture must not already exist. Expected stdout (not executed): a.txt,note.txt Common mistake: Depending on filesystem enumeration order.

Formal Syntax & Structure

rust syntaxrust
fs::read_dir(path) -> io::Result<ReadDir>

Working Example

Example Snippetrust
fn main() {    use std::fs::{self, File, OpenOptions};    use std::io::{Read, Write};    fs::create_dir("bm-fixture").expect("use a fresh disposable directory");    let p = std::path::Path::new("bm-fixture").join("note.txt");    File::create_new(&p).unwrap();    File::create_new(p.with_file_name("a.txt")).unwrap();    let mut names: Vec<_> = fs::read_dir("bm-fixture").unwrap().map(|e| e.unwrap().file_name().into_string().unwrap()).collect();    names.sort();    println!("{}", names.join(","));}
Rust Reference