rust - 将字符串写入文件

标签 rust

pub fn write_file(path: &str, content: &str) -> Result<(), std::io::Error> {
    OpenOptions::new()
        .write(true)
        .create(true)
        .open(path)
        .and_then(|mut file| {
            file.lock_exclusive().and_then(|()| {
                file.write_all(content.as_bytes())
            });
            Ok(())
        })
}

如何修改此方法,使其工作方式与 fprintf 类似:

write_file("/output.txt", "hello, {}. look {}", name, box);

最佳答案

您需要将您的函数设为宏。例如:

macro_rules! write_file {
    ($path: expr, $($content: expr),+) => {{
        OpenOptions::new()
            .write(true)
            .create(true)
            .open($path)
            .and_then(|mut file| {
                file.lock_exclusive().and_then(|()| {
                    write!(file, $($content,)*)
                })
            })
    }}
}

//write_file!("/tmp/foo", "hello {}\n", "world")?;

Playground

如果您打算实际使用它,请务必将 File 包装在 BufWriter 中,以避免将多个微小写入发送到操作系统:

.and_then(|mut file| {
    file.lock_exclusive()?;
    let mut w = BufWriter::new(file);
    write!(w, $($content,)*)?;
    w.flush()   // flush explicitly so write error can propagate
})

关于rust - 将字符串写入文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66686311/

相关文章:

dynamic - 是否可以将特征对象转换为另一个特征对象?

Rust:将值移出选项并压入堆栈

rust - 使用 Rc 和对象安全

rust - 如何修复actix_web中的 “the trait Factory<_, _, _> is not implemented for {function}”错误?

memory - 当第二个维度的大部分为空时,最节省内存的可空向量数组是什么?

multithreading - 线程休眠时跳过部分循环

rust - 具有相同值的多个枚举变体?

rust - 如何通过使用 reqwest 传递 secret 来添加基本授权 header ?

rust - Rust 编译器在多大程度上自动匹配泛型约束?

syntax - 元组、结构和元组结构需要在 Rust 中具有不一致的语法吗?