Note: This site is currently "Under construction". I'm migrating to a new version of my site building software. Lots of things are in a state of disrepair as a result (for example, footnote links aren't working). It's all part of the process of building in public. Most things should still be readable though.

Append To A File In Rust

This is how I append to a file in Rust

Code

use std::fs::OpenOptions;
use std::io::Write;

fn main() {
    append_file("output.txt", "alfa bravo charlie");
}

fn append_file(path: &str, text: &str) {
    println!("Appending file");
    if let Ok(mut file) = OpenOptions::new()
        .create(true).append(true).open(path) {
        if let Err(e) = writeln!(file, "{}", text) {
            eprintln!("Couldn't append: {}", e);
        }
    }
}

References