Search code examples
directoryrust

How to check if a directory exists and create a new one if it doesn't?


I tried the following but I don't think it's particularly pretty:

let path = "target/dir";
if !std::path::Path::new(&path).exists() {
    std::fs::create_dir(path)?;
}

Solution

  • std::fs::create_dir_all:

    Recursively create a directory and all of its parent components if they are missing.

    Examples

    use std::fs;
    
    fs::create_dir_all("/some/dir")?;