Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
329 views
in Technique[技术] by (71.8m points)

rust - Getting the absolute path from a PathBuf

Given a relative path:

PathBuf::from("./cargo_home")

Is there a way to get the absolute path?

question from:https://stackoverflow.com/questions/30511331/getting-the-absolute-path-from-a-pathbuf

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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")

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...