[SOLVED] How create "portable" absolute path


#1

Hi,

I cannot I find a clean way to create an absolute path in a portable way.

Maybe I wrong, but it seems that there is no way to push a root folder at the begging of a PathBuf, so you have to push as first element \ or / depending on which OS the application is running.

There is a better way to do this?

Thank you.

Ciao.


#2

I would think using \ on windows to go to the root would be dangerous. What if they have multiple disks? You would just be going to the root of the current drive.

And sorry I don’t know of a way to do this OS indepdendantly. You might need to use something like the os_type crate to determine which OS you are on and do the correct thing.


#3

Is there ever a reason to create a portable absolute path? You are going to have different paths depending on the system. Think about terminal commands. On linux they are in /bin or /usr/bin or somewhere, on windows they are on C:\windows\system32 or such. You can’t ever have absolute paths to the “same” (for some definition of “same”) file. You should probably rather abstract away the “root” of your folder structure into a function that does something OS-specific, and use relative paths to that “root”. Most of the time you should be working relative to the home directory anyway.


#4

I see your point, actually an cross-platform absolute path doesn’t make sense or maybe it has not real use cases, but anyway I was wondering why it is not possibile to push a root in a clean PathBuf or in general why there is not a method that returns the path folder separator (or maybe is already there and I wasn’t able to find it :blush:).


#5

You can get the separator character for the current OS using the constant std::path:MAIN_SEPARATOR: http://doc.rust-lang.org/stable/std/path/constant.MAIN_SEPARATOR.html

EDIT: you can push this to the beginning of a new PathBuf like this: http://is.gd/Iv6QyY


#6

Thanks… I was looking for a method and I didn’t notice that there is a constant for that!


#7

On Windows a path which begins with \ is not necessarily an absolute path. Paths which being with \\ are typically absolute paths, such as \\.\ device paths or \\?\ verbatim paths or \\UNC\ UNC paths. But if it only begins with a single \ then it is actually a rooted path where it is relative to the root of the current drive. In other words if your current directory is C:\bar and you have a path \foo, it will resolve to C:\foo while if your current directory is D:\meow\meow it will resolve to D:\foo.

For more info see http://googleprojectzero.blogspot.com/2016/02/the-definitive-guide-on-win32-to-nt.html