{

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 File read content into a string

Rust provides a standard library std package that provides an fs module with file read and writes operations. read_to_string function in the fs module takes the path of a file and gives file content into a string. if the file does not exist, It gives an error.

Here is a syntax

pub fn read_to_string<P: AsRef<Path>>(path: P) -> Result<String>

It returns the Result of String, which contains an error as well as String. Here 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 into the console.

The above works if the test.txt file is in the current directory.

If the file is not found, It throws below error thread ‘main’ panicked at ‘Unable to read file: Os { code: 2, kind: NotFound, message: “The system cannot find the file specified.” }’, test.rs:4:46

Rust File read content into a Vector

This example read the file content to 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);

}

The above two work for small files, If you want to read large files, use buffer read.

How to read contents of a file by line in Rust using BufReader

BufferReader in general has a buffer to read File input and output operations efficiently.

  • Create a mutate string for storing file line
  • Create a File object with a path using File::open
  • pass the file instance to the BufReader constructor
  • Call BufReader.read_to_string with a variable that holds file line data -Finally, 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

Learned example program to read the file into string and vector and also read contents line by line in rust.

THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.