Rust: Write a file

Rust: Write a file

Again we’ve already done much of the heavy lifting in terms of learning from just working out how to read a file.

use std::fs::File;
use std::io::{Write};

fn main()  {
    let mut output = File::create("output.txt").expect("Unable to open file");
    write!(output, "Hello\nWorld\n!\n").expect("Unable to write");
}

The file is automatically closed once the reference is out of scope. I quick way to have more control around that is to surround it in braces {} so that the file is closed as soon as we’ve written to it:

use std::fs::File;
use std::io::{Write};

fn main()  {
    {
        let mut output = File::create("output.txt").expect("Unable to open file");
        write!(output, "Hello\nWorld\n!\n").expect("Unable to write");
    }
}

Ordinarily this would be overkill. But it sets us up for the next addition, which is to show you how to open a file so you can append to it (rather than creating/truncating a file like the existing demo did):

use std::fs;
use std::io::{Write};

fn main()  {
    {
        let mut output = fs::File::create("output.txt").expect("Unable to open file");
        write!(output, "Hello\nWorld\n!\n").expect("Unable to write");
    }
    let mut file = fs::OpenOptions::new()
        .write(true)
        .append(true)
        .open("output.txt")
        .expect("Unable to open file");
    write!(file, "and goodbye\n").expect("Unable to write");
}

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.