如何检查路径是否存在?

Jux*_*hin 30 rust

选择似乎介于std::fs::PathExt和之间std::fs::metadata,但后者建议暂时使用,因为它更稳定.以下是我一直在使用的代码,因为它基于文档:

use std::fs;

pub fn path_exists(path: &str) -> bool {
    let metadata = try!(fs::metadata(path));
    assert!(metadata.is_file());
}
Run Code Online (Sandbox Code Playgroud)

但是,由于一些奇怪的原因let metadata = try!(fs::metadata(path))仍然需要函数返回一个,Result<T,E>即使我只是想返回一个布尔值,如图所示assert!(metadata.is_file()).

尽管很快就会有很多变化,但我如何绕过这个try!()问题呢?

以下是相关的编译器错误:

error[E0308]: mismatched types
 --> src/main.rs:4:20
  |
4 |     let metadata = try!(fs::metadata(path));
  |                    ^^^^^^^^^^^^^^^^^^^^^^^^ expected bool, found enum `std::result::Result`
  |
  = note: expected type `bool`
             found type `std::result::Result<_, _>`
  = note: this error originates in a macro outside of the current crate

error[E0308]: mismatched types
 --> src/main.rs:3:40
  |
3 |   pub fn path_exists(path: &str) -> bool {
  |  ________________________________________^
4 | |     let metadata = try!(fs::metadata(path));
5 | |     assert!(metadata.is_file());
6 | | }
  | |_^ expected (), found bool
  |
  = note: expected type `()`
             found type `bool`
Run Code Online (Sandbox Code Playgroud)

She*_*ter 49

请注意,很多时候你想对文件做一些事情,比如读它.在这些情况下,尝试打开它并处理它更有意义Result.这消除了"检查文件是否存在"和"打开文件(如果存在)"之间的竞争条件.如果您真正关心的是它是否存在......

Rust 1.5+

Path::exists......存在:

use std::path::Path;

fn main() {
    println!("{}", Path::new("/etc/hosts").exists());
}
Run Code Online (Sandbox Code Playgroud)

精神指出,Path::exists需要fs::metadata:

pub fn exists(&self) -> bool {
    fs::metadata(self).is_ok()
}
Run Code Online (Sandbox Code Playgroud)

Rust 1.0+

您可以检查fs::metadata方法是否成功:

use std::fs;

pub fn path_exists(path: &str) -> bool {
    fs::metadata(path).is_ok()
}

fn main() {
    println!("{}", path_exists("/etc/hosts"));
}
Run Code Online (Sandbox Code Playgroud)

  • 值得一提的是,`Path :: exists`是`fs :: metadata(path).is_ok()`的别名。 (3认同)
  • @Juxhin 通常最难找到的是简单的答案!^_^ (2认同)

小智 15

您可以使用std::path::Path::is_file

use std::path::Path;

fn main() {
   let b = Path::new("file.txt").is_file();
   println!("{}", b);
}
Run Code Online (Sandbox Code Playgroud)

https://doc.rust-lang.org/std/path/struct.Path.html#method.is_file