为什么这么简单的 BufWriter 操作不起作用



下面的代码非常简单。以写入方式打开一个文件,使用该文件创建一个BufWriter,然后写入一行字符串。

程序没有报告错误并返回Ok(10)值,但文件没有内容并且为空。

#[tokio::test]
async fn save_file_async() {
let path = "./hello.txt";
let inner = tokio::fs::OpenOptions::new()
.create(true)
.write(true)
//.truncate(true)
.open(path)
.await
.unwrap();
let mut writer = tokio::io::BufWriter::new(inner);
println!(
"{} bytes wrote",
writer.write("1234567890".as_bytes()).await.unwrap()
);
}

需要显式刷新:

writer.flush().await.unwrap();

最新更新