OpenOptions Append Log Writes
Open a log with create and append options so writes always extend the file, propagate io errors with ?, and clean the file up when the demo ends.
Code
use std::fs::OpenOptions;
use std::io::{self, Write};
fn append_log(path: &str, line: &str) -> io::Result<()> {
// create + append:文件不存在则建,写入总是追加到末尾不截断
let mut file = OpenOptions::new()
.create(true)
.append(true)
.open(path)?;
writeln!(file, "{line}")
}
fn main() -> io::Result<()> {
let path = "events.log";
append_log(path, "boot")?;
append_log(path, "ready")?;
append_log(path, "shutdown")?;
let contents = std::fs::read_to_string(path)?;
println!("log lines: {}", contents.lines().count());
println!("contains boot: {}", contents.contains("boot"));
std::fs::remove_file(path)?;
Ok(())
}How the snippet works
OpenOptions Append Log Writes comes down to the functions append_log and main.
Fallible operations return Result, and the ? operator short-circuits errors up to the caller.
Caveats
- Errors travel through
Result; if you drop the?operators while adapting, each call site needs its ownmatch.
Applying it
The main signature reads fn append_log(path: &str, line: &str) -> io::Result<()>
Output lines are prefixed (log lines:, contains boot:), making each step’s effect easy to spot.
Start the program and main runs append_log one after another.
Statements that matter
fn append_log(path: &str, line: &str) -> io::Result<()> {
// create + append:文件不存在则建,写入总是追加到末尾不截断
let mut file = OpenOptions::new()
.create(true)
.append(true)
.open(path)?;
writeln!(file, "{line}")
}
let contents = std::fs::read_to_string(path)?;
append_log(path, "shutdown")?;
Interactive Tools for This Topic
FAQ
- How do errors reach the caller?
- Each fallible operation returns `Result`; nothing is silently discarded.
- What does OpenOptions Append Log Writes print when run?
- No setup needed: run the file and look for labeled lines like `log lines:`, `contains boot:` in the output.
Report a problem with this exampleOpens a pre-filled issue on GitHub.