【问题标题】:How can I list files of a directory in Rust?如何在 Rust 中列出目录的文件?
【发布时间】:2014-09-27 15:04:07
【问题描述】:

如何在 Rust 中列出一个目录的所有文件?我正在寻找以下 Python 代码的等价物。

files = os.listdir('./')

【问题讨论】:

  • std::io::fs::readdir

标签: rust


【解决方案1】:

使用std::fs::read_dir()。这里是an example

use std::fs;

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

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

它将简单地遍历文件并打印出它们的名称。

【讨论】:

    【解决方案2】:

    您也可以使用glob,它专门用于此目的。

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

    【讨论】:

    • 这不再起作用了:the trait bound `[u8]: std::marker::Sized` is not satisfied in `std::path::Path` (within `std::path::Path`, the trait `std::marker::Sized` is not implemented for `[u8]`) [E0277] `[u8]` does not have a constant size known at compile-time [E0277] required because it appears within the type `std::path::Path` [E0277] required by `std::vec::Vec` [E0277]
    • Glob 对我来说很好,只需使用自述文件中的示例。
    【解决方案3】:

    这可以通过glob 完成。试试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());
        }
    }
    

    您可能会看到source


    对于递归遍历目录,您可以使用walkdir crate (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());
            }
        }
    }
    

    另请参阅 The Rust CookbookDirectory Traversal 部分。

    【讨论】:

      猜你喜欢
      • 2020-01-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-13
      • 2012-12-09
      • 2012-01-28
      • 1970-01-01
      相关资源
      最近更新 更多