Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to wait until a file is created in Rust?

Tags:

file

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?

like image 321
I60R Avatar asked Jul 10 '18 21:07

I60R


1 Answers

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(())
}
like image 186
I60R Avatar answered Nov 09 '22 18:11

I60R