【发布时间】:2021-03-23 18:45:37
【问题描述】:
我正在使用 serde 将一些数据序列化为 json 格式的文件:
let json = serde_json::to_string_pretty(&data).unwrap();
std::fs::write(&path, &json).expect("Unable to write json file");
向文件添加尾随换行符的最佳方法是什么?
【问题讨论】:
我正在使用 serde 将一些数据序列化为 json 格式的文件:
let json = serde_json::to_string_pretty(&data).unwrap();
std::fs::write(&path, &json).expect("Unable to write json file");
向文件添加尾随换行符的最佳方法是什么?
【问题讨论】:
std::fs::write 只是一个方便的 API。您可以自己写入文件,在这种情况下,您可以在json_serde 完成写入后添加一个换行符,例如:
pub fn save(path: impl AsRef<Path>, data: &impl Serialize) -> std::io::Result<()> {
let mut w = BufWriter::new(File::create(path)?);
serde_json::to_writer_pretty(&mut w, data)?;
w.write(b"\n")?;
w.flush()?;
Ok(())
}
【讨论】: