Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the absolute path from a PathBuf

Tags:

rust

Given a relative path:

PathBuf::from("./cargo_home") 

Is there a way to get the absolute path?

like image 211
Eduardo Bautista Avatar asked May 28 '15 15:05

Eduardo Bautista


People also ask

How do you create an absolute path?

A path is either relative or absolute. An absolute path always contains the root element and the complete directory list required to locate the file. For example, /home/sally/statusReport is an absolute path.

How do you print an absolute path in Python?

Use abspath() to Get the Absolute Path in Python To get the absolute path using this module, call path. abspath() with the given path to get the absolute path. The output of the abspath() function will return a string value of the absolute path relative to the current working directory.

How do you find the absolute path in Ruby?

Pass a string to File. expand_path to generate the path to that file or directory. Relative paths will reference your current working directory, and paths prepended with ~ will use the owner's home directory.


1 Answers

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") 
like image 133
alexwlchan Avatar answered Oct 06 '22 00:10

alexwlchan