Note: This site is currently "Under construction". I'm migrating to a new version of my site building software. Lots of things are in a state of disrepair as a result (for example, footnote links aren't working). It's all part of the process of building in public. Most things should still be readable though.

Check If A File Exists In Rust

Code

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
        }
    }
}

Results

[_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.

References