How to Append to a File in Rust

Append to a file in Rust using OpenOptions with append(true) to add data without overwriting.

Use File::options() with OpenOptions::append(true) to open a file and write to its end without overwriting existing content.

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

fn main() -> std::io::Result<()> {
    let mut file = OpenOptions::new()
        .create(true)
        .append(true)
        .open("data.txt")?;
    
    writeln!(file, "New line appended")?;
    Ok(())
}