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")?;
如果您打算实际使用它,请务必将 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/