I60R
I60R

Reputation: 487

How to wait until a file is created in Rust?

The file may or may not be created before my program starts, so I need to ensure that this file exists before proceeding. What is the most idiomatic way to do that?

Upvotes: 8

Views: 1893

Answers (1)

I60R
I60R

Reputation: 487

Taking into account suggestions from comments I've written the following code:

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

Upvotes: 5

Related Questions