如何等待直到在Rust中创建文件?

时间:2018-07-10 21:19:16

标签: file rust

在我的程序启动之前,可能会或可能不会创建该文件,因此在继续操作之前,我需要确保该文件存在。最惯用的方法是什么?

1 个答案:

答案 0 :(得分:2)

考虑到注释中的建议,我编写了以下代码:

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(())
}