Reading and Writing Files in Rust
As a developer, working with files is an inevitable part of software engineering. In this article, we’ll explore how to read different types of files in Rust, including JSON, YAML, and TOML files. We’ll also cover how to write strings to files.
Accessing a File
To start, we need to create a sample file that we’ll access throughout our project. We can use the write
function provided by the Rust standard library to create a new file called info.txt
.
“`rust
use std::fs;
fn main() {
let contents = “Hello, world!”;
fs::write(“info.txt”, contents).expect(“Something went wrong writing the file”);
}
“`
Reading a File as a String
To read the contents of a file as a string, we can use the read_to_string
function from the fs
module.
“`rust
use std::fs;
fn main() {
let contents = fs::readtostring(“info.txt”).expect(“Something went wrong reading the file”);
println!(“{}”, contents);
}
“`
Reading a File as a Vector
We can also read the contents of a file as a vector of bytes using the read_to_end
method.
“`rust
use std::fs::File;
use std::io::Read;
fn main() {
let mut file = File::open(“info.txt”).expect(“Something went wrong opening the file”);
let mut contents = Vec::new();
file.readtoend(&mut contents).expect(“Something went wrong reading the file”);
println!(“{:?}”, contents);
}
“`
Parsing a Vector of Bytes into a String
If we want to convert the vector of bytes into a string, we can use the `