Rust: Write a file
Mar 25, 2022
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");
}
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 Management, Design, 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.