How to Read a file into string, vector, and line by line Rust example
This tutorial shows multiple ways to read a file in Rust with examples.
Rust: Read File Content into a String
Rust’s standard library, std
, provides an fs
module for file read and write operations. The read_to_string
function within this module takes the path of a file and returns its content as a string. If the file doesn’t exist, it raises an error.
Here is a syntax
pub fn read_to_string<P: AsRef<Path>>(path: P) -> Result<String>
It returns a Result containing either an error or the file content as a String. Below is an example program to read a file into a string in Rust:
use std::fs;
fn main() {
let str = fs::read_to_string("test.txt").expect("Error in reading the file");
println!("{}", str);
}
It displays the string in the console.
The above works if the test.txt file is in the current directory.
If the file is not found, It throws the below error
thread ‘main’ and panicked at ‘Unable to read file: Os { code: 2, kind: NotFound, message: “The system cannot find the file specified.” }’, test.rs:4:46
Rust: Read File Content into a Vector
This example reads the file content into a Vec<u8>
using the read function from the fs
module:
Here is an example program
use std::fs;
fn main() {
let result = fs::read("test.txt").expect("Error in reading the file");
println!("{}", result.len());
println!("{:?}", result);
}
Both methods work well for small files. For large files, it’s recommended to use buffered reading.
How to Read Contents of a File Line by Line in Rust using BufReader
The BufReader
efficiently handles file input and output operations by using a buffer:
- We create a mutable string to store each line of the file.
- We create a File object by opening the file with
File::open
. - We pass the file instance to the
BufReader
constructor. - We call
BufReader.read_to_string
with a variable that holds the file line data. - Finally, we print the data.
use std::fs::File;
use std::io::{BufReader, Read};
fn main() {
let mut str = String::new();
let file = File::open("test.txt").expect("Error in reading file");
let mut bufferReader = BufReader::new(file);
bufferReader.read_to_string(&mut str).expect("Unable to read line");
println!("{}", str);
}
Conclusion
This tutorial has covered example programs to read files into strings and vectors, as well as how to read file contents line by line in Rust.