How to check whether a path exists?

Note that many times you want to do something with the file, like read it. In those cases, it makes more sense to just try to open it and deal with the Result. This eliminates a race condition between "check to see if file exists" and "open file if it exists". If all you really care about is if it exists...

Rust 1.5+

Path::exists... exists:

use std::path::Path;

fn main() {
    println!("{}", Path::new("/etc/hosts").exists());
}

As mental points out, Path::exists simply calls fs::metadata for you:

pub fn exists(&self) -> bool {
    fs::metadata(self).is_ok()
}

Rust 1.0+

You can check if the fs::metadata method succeeds:

use std::fs;

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

fn main() {
    println!("{}", path_exists("/etc/hosts"));
}

You can use std::path::Path::is_file:

use std::path::Path;

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

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

Tags:

Rust