Iterate Directory Entries With read_dir

fs::read_dir returns an iterator of io::Result entries, so each directory item is handled separately and file types come without extra stat calls.

RustData Fetching

Code

rustsnippet
29 lines
use std::fs;

fn main() {
    // 造一个临时目录,避免依赖外部文件
    let dir = std::env::temp_dir().join("read-dir-demo");
    fs::create_dir_all(&dir).expect("create temp dir");
    fs::write(dir.join("a.txt"), "1").unwrap();
    fs::write(dir.join("b.txt"), "2").unwrap();

    // read_dir 返回 ReadDir:元素是 io::Result<DirEntry>,
    // 每个条目单独处理错误,而不是整个目录一起失败
    let mut names: Vec<String> = Vec::new();
    for entry in fs::read_dir(&dir).expect("read dir") {
        let entry = entry.expect("entry readable");
        names.push(entry.file_name().to_string_lossy().into_owned());
    }

    // 文件系统给出的顺序不保证稳定:排序后输出才一致
    names.sort();
    for name in &names {
        println!("entry: {name}");
    }

    // DirEntry::file_type 免去额外 stat 调用
    let first = fs::read_dir(&dir).unwrap().next().unwrap().unwrap();
    println!("first is file: {}", first.file_type().unwrap().is_file());

    fs::remove_dir_all(&dir).unwrap();
}

How it works

Count the function main as the entire surface area of Iterate Directory Entries With read_dir.

Repetition is confined to for entry in fs::read_dir(&dir).expect("read dir") — the rest of the file is straight-line.

Putting it to use

Look for the entry:, first is file: prefixes when the file runs; they tie each line to its step.

Core lines

let first = fs::read_dir(&dir).unwrap().next().unwrap().unwrap();
fs::write(dir.join("a.txt"), "1").unwrap();
fs::write(dir.join("b.txt"), "2").unwrap();

FAQ

What does Iterate Directory Entries With read_dir print when run?
Execute the whole file; each printed line is prefixed with a label like `entry:`, `first is file:`.