Rust: Read a file

Mar 25, 2022

There's a simple one-shot was to read a file in as a string:

use std::fs;

fn main() {
    let s = fs::read_to_string("input.txt").expect("Unable to read file");
    println!("as string: {}", s);
}

Or if you need to do the equivalent but as a vector of bytes:

use std::fs;
use std::str;

fn main() {
    let d = fs::read("input.txt").expect("Unable to read file");
    let data = str::from_utf8(&d).expect("Unable to convert bytes to string");
    println!("as vector of bytes, length: {} as data: {}", d.len(), data);
}

To read a file incrementally you'll instead open() it and then iterate over the lines():

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

fn main() {
    let input = fs::File::open("input.txt").expect("Unable to open file");
    let buffered = BufReader::new(input);

    for line in buffered.lines() {
        println!("line: {}", line.expect("error reading line"));
    }

}
Hi, I'm Glenn! 👋 I'm currently Director of Product (Terraform) @ HashiCorp, and we're hiring! If you'd like to come and work with me and help make Terraform Cloud even more amazing we have multiple positions opening in Product ManagementDesign, and Engineering & Engineering Management across a range of levels (i.e., junior through to senior). Please send in an application ASAP so we can get in touch.