HiveBrain v1.2.0
Get Started
← Back to all entries
snippetrustCritical

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

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
directoryhowcheckandexistsdoesnonenewcreate

Problem

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")?;

Code Snippets

use std::fs;

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

Context

Stack Overflow Q#48053933, score: 116

Revisions (0)

No revisions yet.