In this article, we will explore how to work with files in Rust by creating a file to the filesystem and adding some content to it.
We assume you have the Rust compiler installed and the necessary tools.
Set up Project Structure
The first step is to set up the structure for our program. We will use cargo that will set up everything required for us:
The previous command should create a directory structure holding the source code for your program.
Navigate to the src directory and open the main.rs file with your text editor.
By default, cargo will add the hello world program to the main.rs file to any new project. You can delete the contents and start with the bare minimum.
To create and write a file, we will need to import a few modules from the Rust standard library.
In this step, we will need the file struct and the prelude module. The import statements are as shown below:
Create and Write to File
Next is the main function. We can do this using the fn keyword as:
Inside the main function, we start by defining a new variable that will be mutable. For example. the code is as follows:
In the previous example, we create a mutable variable holding the file to create. The path to the file is specified as string.
Sometimes, Rust may encounter an error when attempting to create the file. We can include a small error handling mechanism to the create method using the “expect” keyword.
.expect("Error encountered while creating file!");
The previous example should print the provided message if the compiler encounters an error while creating the specified file.
Once we have the file created, we can start writing to it. For the sake of simplicity, we write a simple string to the file.
We can do this using the write_all method. The method takes a byte slice which to write to the file. We can do this by appending a “b” as the prefix to the string we wish to the file.
The following code is as shown:
.expect("Error while writing to file");
In the previous example, we used the write_all method to write a byte slice to the file. We also added the expect method to handle any errors encountered while writing to the file.
And with that, we have created a new file and written on it. You can run and test the previous program using the cargo command as:
The program should create a new file called hello.txt if it does not exist in the specified path. If the file exists, the program will empty the file and write the specified string:
Hi, Welcome to Rust Programming!
This article covered how to create and write a file using the Rust programming language. In addition, we discussed the expect method. We hope you found this article helpful. Check the other Linux Hint articles for more tips and information.