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.
Additionally since we are working with unix permissions we will import the DirBuilderExt impl.
Define our Function
Create a new DirBuilder object
Set the builder to create directories recursively if needed
Set the permissions on the builder
Create the directories
Final Function
Below is the final form of our function that will recursively create directories in rust and set permissions on unix machines.