home ~ projects ~ socials

Check If A File Exists In Rust

use std::path::PathBuf;

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

fn file_exists(path: &PathBuf) -> bool {
    match path.try_exists() {
        Ok(exists) => {
            if exists == true {
                true
            } else {
                false
            }
        }
        Err(_) => {
            false
        }
    }
}
Output:
[_active_nvim_run:5:5] file_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 --

References