Rust, Software Development

Ways to Create Temporary Files In Rust

Creating temporary files in Rust is sometimes essential when we need to use the files once or cache data for a short time. We then let the operating system delete the files at a later time automatically or by its clean-up feature manually.

Operating System Temporary Directory

To benefit from the auto-deletion, we must create temporary files in directories the operating system looks for files to delete. Hence, we need to get the temp directory. In Rust, we can use the temp_dir ( std::env::temp_dir) function to that end.

The codes generate the following output.

For Unix, the temp_dir function returns directory specified for the TMPDIR environment. Otherwise, it returns /tmp.  For Android operating system, the temp_dir function returns /data/local/tmp.

For Windows, the function works a little bit differently. The function first checks the TMP environment for value. If TMP is empty, it then checks the TEMP environment. When TEMP is empty or undefined, the function then checks the USERPROFILE environment. If USERPROFILE is still undefined, the function returns the Windows directory.

Create Temporary Files in Rust

Temporary files typically have unique names to ensure that our codes refer to a file it had created and used at a particular instance. We could use UUIDs as file names.

In the Cargo.toml, update the dependencies as follows.

Then, we can use to generate UUIDs.

When we run the codes, we get the following output.

We can then verify the codes generated a file with the same name.

Using the  tempfile crate

In case we do not want to reinvent the wheels, there is a crate available for creating temporary files and even directories. The tempfile crate has the following functions and structs for dealing with temporary files and directories.

To use the crate, update Cargo.toml as follows.

The tempfile() and tempdir() functions create files and directories and rely on the underlying operating system to remove them when handles close. The following codes create a temporary file and a temporary directory.

We get the following output.

We will not be able to see the files and directories when the application completes execution. The operating system deletes them when the handles close.

The structs NamedTempFile and TempDir work the same way but require explicit deletion via their destructors. Consider the following codes.

The output is as follows.

Loading

Got comments or suggestions? We disabled the comments on this site to fight off spammers, but you can still contact us via our Facebook page!.


You Might Also Like