Extracting relative path in PathBuf

i have pathbuf which looks like this

let p :PathBuf = PathBuf::new("/path/to/file/file.txt"); // Here p has absolute path of file.txt

i want to create a new PathBuf variable from p which will have relative path
i.e

q : PathBuf = file/file.txt

How do i do this?

The most straightforward way to do this is with the Path::strip_prefix() method.

let path = Path::new("/test/haha/foo.txt");

assert_eq!(path.strip_prefix("/"), Ok(Path::new("test/haha/foo.txt")));
assert_eq!(path.strip_prefix("/test"), Ok(Path::new("haha/foo.txt")));
assert_eq!(path.strip_prefix("/test/"), Ok(Path::new("haha/foo.txt")));
assert_eq!(path.strip_prefix("/test/haha/foo.txt"), Ok(Path::new("")));
assert_eq!(path.strip_prefix("/test/haha/foo.txt/"), Ok(Path::new("")));

It's a purely text-based method though, and doesn't take into account symlinks and the like.

2 Likes

You could use an iterator for that maybe? Hard to guess what the underlying algorithm for extraction is with only your example.

use std::path::PathBuf;

fn main() {
    let p: PathBuf = PathBuf::from("/path/to/file/file.txt");
    
    let q: PathBuf = p.iter().skip(3).collect();
    
    assert_eq!(q, PathBuf::from("file/file.txt"));
}

Playground.

Relative to what?

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.