< 返回版块

2019-10-24 23:34    责任编辑:jay

标签:Tyro,Novice,Try

递归: Using std::fs::walk_dir (unstable as of Rust 1.1) with imperative for-loop:


#![feature(fs_walk)]  
   
use std::fs;  
use std::path::Path;  
   
fn main() {  
    for f in fs::walk_dir(&Path::new("/home/pavel/Music")).unwrap() {  
        let p = f.unwrap().path();  
        if p.extension().unwrap_or("".as_ref()) == "mp3" {  
            println!("{:?}", p);  
        }  
    }  
}

非递归:


extern crate docopt;
extern crate regex;
extern crate rustc_serialize;
 
use docopt::Docopt;
use regex::Regex;
 
const USAGE: &'static str = "
Usage: rosetta <pattern>
 
Walks the directory tree starting with the current working directory and
print filenames matching <pattern>.
";
 
#[derive(Debug, RustcDecodable)]
struct Args {
    arg_pattern: String,
}
 
fn main() {
    let args: Args = Docopt::new(USAGE)
        .and_then(|d| d.decode())
        .unwrap_or_else(|e| e.exit());
 
    let re = Regex::new(&args.arg_pattern).unwrap();
    let paths = std::fs::read_dir(".").unwrap();
 
    for path in paths {
        let path = path.unwrap().path();
        let path = path.to_str().unwrap();
 
        if re.is_match(path) {
            println!("{}", path);
        }
    }
}