Rust, How to Read a File

Mike Code
2 min readJun 2, 2024

--

First , the simplest way is read_to_string function from fs:

use std::fs::read_to_string;

fn main() {
let content = read_to_string("hello.txt").unwrap();
println!("{}", content)
}

We call read_to_string function from fs, pass a path as argument , we need to call unwrap to handle the result read_to_string returns, if succeed, it will return the string content from result to variable content, if fail it will panic.

Second ,

use std::{fs::File, io::Read};

fn main() {
let mut file = File::open("hello.txt").unwrap();
let mut buf = Vec:: new();
file.read_to_end(&mut buf).unwrap();
match String::from_utf8(buf) {
Ok(text) => println!("{}", text),
Err(e) => println!("{}", e)
}
}

We call open function from File , pass a path into this function , to open a file , then we need to call unwrap to handle result if open file failed, We store file into a mutable variable named file .

We create a mutable buffer variable, which is an empty mutable vector.

We call read_to_end method on file (we need to import Read trait from io), to read content from file to the buffer , we pass mutable reference vector as argument , it will store content of u8 in this buf vector, and we also need to call unwrap to handle the result.

We create a match expression , when we call from_utf8 function from String to convert u8 buffer to String value , we add two arms , first if convert successfully it will be an Ok ,we will print text in an Ok, if fails, it will return an Err, we will print error message in the Err.

Third,

use std::{fs::File, io::{BufRead, BufReader}};

fn main() {
let file = File::open("hello.txt").unwrap();
let buf_reader = BufReader::new(file);
for line in buf_reader.lines() {
let line = line.unwrap();
println!("{}", line)
}
}

We call open from File to open a file from a path.

We call new function from BufReader to create a new BufReader, we pass file into this bufreader.

We create a for loop, we call lines method on buf_reader ,it will return an iterator of each line in a result from this buf_reader, in for loop, we iterate each line, each line in a result, we need to call unwrap to handle result, last print each line .

--

--