Hello Rustaceans! This guide will teach you to read files using the Rust programming language.
Sample File
Although you can read a file stored in any location of your filesystem, for illustration, we will keep our sample file in the current working directory.
Start by generating a new project as:
Next, navigate into the directory as:
Inside the src directory, create a sample test file.
echo "Hi, I am inside the sample.txt file" > sample.txt
The previous commands will create a new text file and write it to the sample.txt file.
Read File as a String
The simplest method to read a file is to read it as a string. This method loads the file’s contents into memory and allows you to manipulate the file.
We can do this using the read_to_string method from the Read module of the io package. An example is provided below:
use std::io::Read;
fn main() {
let mut file = File::open("sample.txt")
.expect("Error opening file");
let mut data = String::new();
file.read_to_string(&mut data)
.expect("Error reading file");
println!("{}", data);
}
In the previous code, we started by importing the required modules for handling files. These include the fs::File and io::Read from the standard library.
The first statement in the main function creates a mutable handle to the file we wish to open. We do this by using the File::open method and pass the name of the file as the argument.
The second statement holds a mutable variable containing the data of the file. We create this as an empty string to which we can then load the data of the file.
Finally, we call the read_to_string method to read the file and pass a mutable reference to the data variable. This will write the contents of the file to the empty string.
Then, we can print the contents of the file using the println! method.
Running the previous code should return the content in the sample.txt
Hi, I am inside the sample.txt
Read File Line by Line
We can read a file line by line using the lines() method. Consider the example code shown below:
use std::io::BufReader;
use std::io::prelude::*;
fn main() -> std::io::Result<()>{
let file = File::open("sample.txt")
.expect("Error opening file");
let mut reader = BufReader::new(file);
for line in reader.lines() {
println!("{}", line?);
}
Ok(());
}
The previous code uses the File::open() method to read the sample.txt. The following line creates a mutable reader using the BufReader::new and passes the file object. Then, we iterate the lines in the file and print the contents.
Conclusion
In this article, we covered two major methods of reading files in the Rust programming language. Although the code implemented in this article works great for small files, it can quickly get complex with extensive files. Hence, consider organizing the read operations into standalone functions. This can help reduce the load on the main function. We hope you found this article helpful. Check the other Linux Hint articles for more tips and information.