Peter Girnus

View Original

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.

See this content in the original post

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

See this content in the original post

Define our Function

See this content in the original post

Create a new DirBuilder object

See this content in the original post

Set the builder to create directories recursively if needed

See this content in the original post

Set the permissions on the builder

See this content in the original post

Create the directories

See this content in the original post

Final Function

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

See this content in the original post