Home
Head's Up: I'm in the middle of upgrading my site. Most things are in place, but there are something missing and/or broken including image alt text. Please bear with me while I'm getting things fixed.

Append To A File In Rust

This is how I append to a file in Rust

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

- The [TODO: Code shorthand span ] makes the file if it doesn't already exist. Without that, the process will throw an error if the file isn't already there.

- Could also update it to return a result for things working or not. I haven't needed that yet. I expect it'll come in hand at some point.

Footnotes And References