在我的程序启动之前,可能会或可能不会创建该文件,因此在继续操作之前,我需要确保该文件存在。最惯用的方法是什么?
最佳答案
考虑到评论的建议,我编写了以下代码:
fn wait_until_file_created(file_path: &PathBuf) -> Result<(), Box<Error>> {
let (tx, rx) = mpsc::channel();
let mut watcher = notify::raw_watcher(tx)?;
// Watcher can't be registered for file that don't exists.
// I use its parent directory instead, because I'm sure that it always exists
let file_dir = file_path.parent().unwrap();
watcher.watch(&file_dir, RecursiveMode::NonRecursive)?;
if !file_path.exists() {
loop {
match rx.recv_timeout(Duration::from_secs(2))? {
RawEvent { path: Some(p), op: Ok(op::CREATE), .. } =>
if p == file_path {
break
},
_ => continue,
}
}
}
watcher.unwatch(file_dir)?;
Ok(())
}
关于file - 如何等待直到在Rust中创建文件?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/51274039/