Rust file reading
last modified February 19, 2025
In this article, we will cover how to read files in Rust.
Rust has several ways to read files, including using the
std::fs::File
and std::io::Read
traits.
The read_to_string function
The read_to_string
function reads the whole file into a
String
.
use std::fs::File; use std::io::Read; fn main() { let filename = "words.txt"; let mut file = match File::open(filename) { Ok(file) => file, Err(err) => panic!("Could not open file: {}", err), }; let mut contents = String::new(); match file.read_to_string(&mut contents) { Ok(_) => println!("File contents: {}", contents), Err(err) => panic!("Could not read file: {}", err), } }
In this example, we open a file called words.txt
using the
File::open
function and read its contents into a string using the
read_to_string
function.
Using BufReader
Another way to read files in Rust is to use the BufReader
type from
the std::io
module.
use std::fs::File; use std::io::{BufRead, BufReader}; fn main() { let filename = "words.txt"; let file = match File::open(filename) { Ok(file) => file, Err(err) => panic!("Could not open file: {}", err), }; let reader = BufReader::new(file); for line in reader.lines() { match line { Ok(line) => println!("{}", line), Err(err) => panic!("Could not read line: {}", err), } } }
In this example, we open a file and create a BufReader
instance to
read the file line by line.
The read_to_end function
The read_to_end
function reads all bytes until EOF in the source,
placing them into a buffer.
use std::fs::File; use std::io::{self, Read}; fn main() -> io::Result<()> { let filename = "words.txt"; let mut f = File::open(filename)?; let mut buffer = Vec::new(); f.read_to_end(&mut buffer)?; let content = String::from_utf8_lossy(&buffer); println!("{}", content); Ok(()) }
In this example, we define a buffer and read the while file into the buffer
with read_to_end
. Later we convert the buffer into a string
and print it to the console.
let mut buffer = Vec::new();
We define a buffer.
f.read_to_end(&mut buffer)?;
We read the whole file into a buffer.
let content = String::from_utf8_lossy(&buffer);
We convert the buffer to a string.
In this article, we covered the basics of reading files in Rust. We demonstrated
how to open and read files using the std::fs::File
and
std::io::Read
traits, and how to handle errors that may occur
during the process.
Author
List all Rust tutorials.