Suppose I have the following three paths:
let file = path::Path::new("/home/meurer/test/a/01/foo.txt");
let src = path::Path::new("/home/meurer/test/a");
let dst = path::Path::new("/home/meurer/test/b");
Now, I want to copy file
into dst
, but for that I need to correct the paths, so that I can have new_file
with a path that resolves to /home/meurer/test/b/01/foo.txt
. In other words, how do I remove src
from file
and then append the result to dst
?
/home/meurer/test/a/01/foo.txt
-> /home/meurer/test/b/01/foo.txt
Note that we can't assume that src
will always be this similar to dst
.
You can use Path::strip_prefix
and Path::join
:
use std::path::Path;
fn main() {
let file = Path::new("/home/meurer/test/a/01/foo.txt");
let src = Path::new("/home/meurer/test/a");
let dst = Path::new("/home/meurer/test/b");
let relative = file.strip_prefix(src).expect("Not a prefix");
let result = dst.join(relative);
assert_eq!(result, Path::new("/home/meurer/test/b/01/foo.txt"));
}
As usual, you probably don't want to use expect
in your production code, it's only for terseness of the answer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With