How to Check Whether a Path Exists in Rust

Created
Modified

Using Path::exists Function

The Path::exists() function returns true if the path points at an existing entity.

See the following example:

// Rust 1.5+
use std::path::Path;

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

If you want to check errors, call fs::metadata:

use std::fs;

fn main() -> std::io::Result<()> {
  let metadata = fs::metadata("file.txt")?;

  println!("{:?}", metadata.file_type());
  Ok(())
}
FileType(FileType { mode: 33252 })

Related Tags

#check# #path#