Rust: Read a file

Rust: Read a file

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"));
    }

}

Published: 25/03/2022

Hi, I'm Glenn! 👋

I've spent most of my career working with or at startups. I'm currently the VP of Product / GTM @ Ockam where I'm helping developers build applications and systems that are secure-by-design. It's time we started securely connecting apps, not networks.

Previously I led the Terraform product team @ HashiCorp, where we launched Terraform 1.0, Terraform Cloud, and a whole host of amazing capabilities that set the stage for a successful IPO. Prior to that I was part of the Startup Team @ AWS, and earlier still an early employee @ Heroku. I've also invested in a couple of dozen early stage startups.