How can I list files of a directory in Rust?

2019-04-03 07:23发布

问题:

How can I list all the files of a directory in Rust? I am looking for the equivalent of the following Python code.

files = os.listdir('./')

回答1:

Here's an example:

use std::fs;

fn main() {
    let paths = fs::read_dir("./").unwrap();

    for path in paths {
        println!("Name: {}", path.unwrap().path().display())
    }
}

It will simply iterate over the files and print out their names.



回答2:

You could also use glob, which is expressly for this purpose.

extern crate glob;
use self::glob::glob;

let files:Vec<Path> = glob("*").collect();


回答3:

Try this on the playground:

extern crate glob;
use glob::glob;
fn main() {
    for e in glob("../*").expect("Failed to read glob pattern") {
        println!("{}", e.unwrap().display());
    }
}

You may see the source.


And for walking directories recursively try this on the playground:

extern crate walkdir;
use walkdir::WalkDir;
fn main() {
    for e in WalkDir::new(".").into_iter().filter_map(|e| e.ok()) {
        if e.metadata().unwrap().is_file() {
            println!("{}", e.path().display());
        }
    }
}

See walkdir, and Directory Traversal.

I hope this helps.



标签: rust