Given a relative path:
PathBuf::from("./cargo_home")
Is there a way to get the absolute path?
It seems I can't delete this answer while it is accepted. See this answer for a more current and complete answer.
If I understand the PathBuf documentation correctly it does not treat "./" as a special start to a path that says its relative.
You can however turn a relative path into an absolute one with 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 that your relative path is relative to your current directory.
./x, you end up with the . as part of the result, whereas they might be expecting it not to show up. The distinction is important if you're trying to get a (within the limits imposed by hard links) canonical path to a file.
– DK.
May 29 '15 at 14:52
Rust 1.5.0 added 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")
canonicalize (as of Rust 1.31) adds the Extended length path prefix ` \\?\ ` to the path (see docs.microsoft.com/en-us/windows/desktop/FileIO/…). Make sure the consumer of the canonicalized path is aware of that.
– Tomáš Dvořák
Dec 18 at 13:27