Rust std::fs: Creating Directories with DirBuilder

This mini how-to focuses on creating directories in Rust using the DirBuilder impl which is part of the Rust standard library (source code).

The DirBuilder impl is part of the DirBuilder Struct contained in the std::fs module (filesystem manipulation operations) which allows us to use Rust to manipulate the filesystem.

This mini how-to will first define a simple problem and then work out the solution. Let’s define our problem first.

Problem

We would like to create a rust function that takes a path argument which is the directory (or directories) path we want to create using Rust. This created function will also accept a u32 primitive which will be the permission level in unix octal format. Let’s get to work.

Solution

Let’s solve the problem with the following steps:

Import required libraries

To begin we need to import the std::fs module using the following declaration.

use std::fs;

Additionally since we are working with unix permissions we will import the DirBuilderExt impl.

use std::os::unix::fs::DirBuilderExt;

Define our Function

fn create_directories(path_str: &str, permission_u32: u32) {
// NEXT STEPS GO HERE
}

Create a new DirBuilder object

let mut builder = fs::DirBuilder::new();

Set the builder to create directories recursively if needed

builder.recursive(true);

Set the permissions on the builder

builder.mode(permission_u32);

Create the directories

match builder.create(path_str) {
        Ok(()) => println!("The path {:?} was created!", path_str),
        Err(e) => println!("ERROR: {:?}", e)
}

Final Function

Below is the final form of our function that will recursively create directories in rust and set permissions on unix machines.

Previous
Previous

Rust std::fs: Parsing Directories & File Entries with DirEntry

Next
Next

Scanning Files With Regular Expressions (RegEx) In Rust