home ~ socials ~ projects ~ rss

Check if a File or Directory Path Exists in Rust

June 2023
use std::path::PathBuf;

fn main() {
    let file_path = PathBuf::from("files/alfa.txt");
    dbg!(path_exists(&file_path));
}

pub fn path_exists(path: &PathBuf) -> bool {
    match path.try_exists() {
        Ok(exists) => {
            if exists == true {
                true
            } else {
                false
            }
        }
        Err(_) => {
            false
        }
    }
}
Output:
[_active_nvim_run:5:5] path_exists(&file_path) = true

The is the basic way to check if a file exists using `.try_exists()`rust` instead of `.exists()`rust`. The difference between the two is that `.try_exists()rust will produce an Err for things like permissions issues or broken symbolic links.

end of line
Share link:
https://www.alanwsmith.com/en/2r/tg/5n/3b/?check-if-a-file-or-directory-path-exists-in-rust