Drop current directory from abs path


Is there an elegant way to drop the current directory as a prefix from an absolute path, leaving only the subdirectories and the file?

Or is it creating a relative path from an absolute path? Either way, I can't find anything specific. Do I have to get down to the strings?

Found an example. The compiler says

919 |         let rel = p.relative_from("/home/user").unwrap();
    |                     ^^^^^^^^^^^^^ method not found in `&PathBuf`

Very interesting.

Does strip_prefix do what you're looking for? (And if not, how is it lacking.)

Yes, this is what I need. Thanks! I'm still curious about relative_from():

fn main() {
    let path = PathBuf::from("/home/user/.dotfile");
    let rel_path = path.relative_from("/home/user").unwrap();
    println!("{}", path.display());
    println!("{}", rel_path.display());
    if is_dot(&PathBuf::from(rel_path)) {
        println!("{} is dot", rel_path.display());

from here.

Looks like relative_from was the pre-stabilization name for strip_prefix, because all paths used to be normalized apparently. They're not any more, and strip_prefix is a lexical operation more than anything, hence the name change. As far as I know, a post-normalization version doesn't exist in stdlib, though you could call canonicalize on both arguments first.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.