home
NOTE: Under Construction - I'm in the middle of upgrading my site and lots of stuff is kinda broken. Please forgive the mess.

Create A Directory In Rust If It Doesn't Already Exist

June 2023

This is the function I use to make sure a directory exists before trying to do something with it. If the target directory doesn't exist, it'll be made recursively. If it can't be made for some reason it'll throw an error. Note that just because the directory exists doesn't mean the permissions are writeable.

Code
use std::fs;
use std::path::PathBuf;

fn main() {
    let path = PathBuf::from("verify-exists/sub-path");
    match verify_dir(&path) {
        Ok(()) => println!("Verified the directory exists"),
        Err(e) => println!("{}", e)
    }
}

fn verify_dir(dir: &PathBuf) -> std::io::Result<()> {
    if dir.exists() {
        Ok(()) 
    } else {
        fs::create_dir_all(dir)
    }
}
Results
Verified the directory exists
═══ § ═══