Getting absolute path from PathBuf

Given the relative path:

PathBuf::from("./cargo_home") 

Is there any way to get the absolute path?

+14
rust
source share
2 answers

Rust 1.5.0 added std::fs::canonicalize , which sounds pretty close to what you want:

Returns the canonical form of the path with all normalized intermediate components and resolved symbolic links.

Note that unlike the accepted answer, this removes ./ from the returned path.


A simple example from my car:

 use std::fs; use std::path::PathBuf; fn main() { let srcdir = PathBuf::from("./src"); println!("{:?}", fs::canonicalize(&srcdir)); let solardir = PathBuf::from("./../solarized/."); println!("{:?}", fs::canonicalize(&solardir)); } 
 Ok("/Users/alexwlchan/Developer/so-example/src") Ok("/Users/alexwlchan/Developer/solarized") 
+29
source share

If I understand the PathBuf documentation correctly, it does not consider "./" as a special start to the path that talks about its relative.

However, you can turn a relative path into an absolute path using std::env::current_dir :

 let relative_path = PathBuf::from("cargo_home"); let mut absolute_path = try!(std::env::current_dir()); absolute_path.push(relative_path) 

This assumes your relative path relative to your current directory.

+6
source share

All Articles