Skip to main content

path_helper/sync/
safe_replace.rs

1use crate::sync::gen_unique_path;
2use std::{io::Write, path::Path};
3
4/// 安全的替换文件内容。会在同目录下创建一个临时文件,落盘完成后再重命名回原文件。
5pub fn safe_replace(path: &Path, content: &[u8]) -> std::io::Result<()> {
6    let tmp_path = gen_unique_path(path.with_extension("tmp"))?;
7    let mut file = std::fs::OpenOptions::new()
8        .truncate(true)
9        .create(true)
10        .write(true)
11        .open(&tmp_path)?;
12    file.write_all(content)?;
13    file.sync_all()?;
14    std::fs::rename(tmp_path, path)?;
15    Ok(())
16}