Copy A Directory Recursively In Rust Without std::fs::copy
```cargo
[dependencies]
walkdir = "2.5.0"
```
use std::fs;
use std::path::PathBuf;
use walkdir::WalkDir;
fn main() {
let source = PathBuf::from("target_source");
let dest = PathBuf::from("target_dest");
match copy_dir(&source, &dest) {
Ok(_) => { println!("copied the directory"); }
Err(e) => { println!("{:?}", e); }
}
}
fn copy_dir(source_dir: &PathBuf, dest_dir: &PathBuf) -> Result<(), std::io::Error> {
for entry in WalkDir::new(source_dir) {
let source_path = entry?.into_path();
let dest_path = dest_dir.join(source_path.strip_prefix(source_dir).unwrap());
if source_path.is_dir() {
fs::create_dir_all(dest_path)?;
}
else {
let data = std::fs::read(source_path)?;
std::fs::write(dest_path, &data)?;
}
}
Ok(())
}
Notes
-
There's an issue with notify and std::fs::copy where copying a file triggers an event. That means you can't watch and copy files the way you'd expect because they keep triggeing themselves
-
This is very naive (e.g. it doesn't deal with links or have substantial error handling)