Parse a file in Rust

August 24, 2022  ‐ 1 min read

To parse the contents of a file in Rust we make use of std::fs from the standard library. Where fs is short for filesystem. Using read_to_string() we can read the file contents.

use std::fs;

fn main() {
    let file_contents = fs::read_to_string("/home/koen/.vimrc").expect("Unable to read file");
    println!("{}", file_contents);
}

To loop over the lines in the file we can call lines() to get an iterator.

use std::fs;

fn main() {
    let file_contents = fs::read_to_string("/home/koen/.vimrc").expect("Unable to read file");

    for line in file_contents.lines() {
        println!("{}", line);
    }
}