我知道我可以调用
drop
显式关闭 fd。但是如果该文件在循环内使用怎么办?
我可以在不使用不安全代码块的情况下处理它吗?
假设这个场景: 我想每10秒写入一个文件,并且这个文件每10分钟就会更改一次。文件名由时间戳生成。
let mut file = File::create("ts1").unwrap();
loop {
file.write(buf).unwrap();
if time_elapsed() > 10 * 60 {
// how to close the old fd?
// drop cannot be used because it is inside the loop
file = File::create("ts2").unwrap();
}
thread::sleep(Duration::from_secs(10));
}
我相信您正在寻找一种将文件对象上完成的操作同步到磁盘的方法。在这种情况下,您不需要删除对象,而是调用
sync_all
。
let mut file = File::create("ts1").unwrap();
loop {
file.write(buf).unwrap();
if time_elapsed() > 10 * 60 {
// how to close the old fd?
// drop cannot be used because it is inside the loop
let _ = file.sync_all();
file = File::create("ts2").unwrap();
}
thread::sleep(Duration::from_secs(10));
}