Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a folder to a path before the filename?

How do I change "C:\foo\bar.txt" to "C:\foo\baz\bar.txt" using either Path or PathBuf?

I want to add a folder to the path immediately before the filename.

like image 496
GirkovArpa Avatar asked Oct 24 '25 17:10

GirkovArpa


1 Answers

The Path type supports a number of methods to manipulate and destructure paths, so it should be straightforward to append a directory. For example:

fn append_dir(p: &Path, d: &str) -> PathBuf {
    let dirs = p.parent().unwrap();
    dirs.join(d).join(p.file_name().unwrap())
}

I'm testing it on Linux, so for me the test looks like this, but on Windows you should be able to use C:\... just fine:

fn main() {
    let p = Path::new(r"/foo/bar.txt");
    assert_eq!(append_dir(&p, "baz"), Path::new(r"/foo/baz/bar.txt"));
}
like image 129
user4815162342 Avatar answered Oct 26 '25 09:10

user4815162342