patternrustCritical
Getting the absolute path from a PathBuf
Viewed 0 times
fromgettingabsolutethepathbufpath
Problem
Given a relative path:
Is there a way to get the absolute path?
PathBuf::from("./cargo_home")Is there a way to get the absolute path?
Solution
Rust 1.5.0 added
Returns the canonical form of a path with all intermediate components normalized and symbolic links resolved.
Note that, unlike the accepted answer, this removes the
A simple example from my machine:
std::fs::canonicalize, which sounds pretty close to what you want:Returns the canonical form of a path with all intermediate components normalized and symbolic links resolved.
Note that, unlike the accepted answer, this removes the
./ from the returned path.A simple example from my machine:
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")
Code Snippets
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));
}Context
Stack Overflow Q#30511331, score: 108
Revisions (0)
No revisions yet.