We already know how to write to a file, but that way we overwrite the whole file losing any content it had earlier. In most cases that's what we really want. Sometimes, however, especially in the case of log-files, we would want to keep the original content and append something to the end of the file.
We can accomplish this by opening the File in append
mode.
We do that by using the options method.
We can stack the various modes on each other.
In this case we set both the append
and the create
mode to true
.
The actual writing is the same as in the other case using the writeln! macro.
examples/files/append-to-file/src/main.rs
use std::env;
use std::error::Error;
use std::fs::File;
use std::io::Write;
use std::process::exit;
fn main() -> Result<(), Box<dyn Error>> {
let args = env::args().collect::<Vec<String>>();
if args.len() != 2 {
eprintln!("Usage: {} MESSAGE", args[0]);
exit(1);
}
let message = &args[1];
let filename = "messages.txt";
let mut file = File::options()
.append(true)
.create(true)
.open(filename)?;
writeln!(&mut file, "{message}")?;
Ok(())
}
Usage of the example:
cargo run -q hello
cargo run -q "second row"
cargo run -q "3rd row"
The result will be a file called "messages.txt" with all those lines.