← 中文资源

简体中文版本

OpenOptions 追加写日志

OpenOptions 用 create 与 append 组合打开日志文件:写入总是追加到末尾不截断,io 错误用 ? 逐层传播,收尾删除文件保持目录干净。

阅读英文原文

实现说明

OpenOptions 追加写日志可以归结为函数 append_log、main。 错误装在 Result 里往回传,迫使每个调用点显式决策。

使用要点

  • 错误处理是类型化的——每个 Result 都要 match 或用 ? 转发。
  • 每一步打印都带着自己的标签:log lines:、contains boot:。
  • 执行文件,main 会按顺序走完 append_log。

常见问题

错误怎么传到调用方?

每个可能失败的操作都返回 Result,不会被悄悄丢弃。

运行「OpenOptions 追加写日志」会打印什么?

整个文件跑完,输出行以 log lines:、contains boot: 这类前缀开头。

主签名形如 fn append_log(path: &str, line: &str) -> io::Result<()>

核心语句

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")?;

代码示例

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(())
}