Home
Head's Up: I'm in the middle of upgrading my site. Most things are in place, but there are something missing and/or broken including image alt text. Please bear with me while I'm getting things fixed.

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

rust
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 start

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.