Get Absolute path from relative path

Post your working scripts, libraries and tools.
User avatar
Maestr0
Posts: 136
Joined: 05 Dec 2013, 17:43

Get Absolute path from relative path

13 Aug 2019, 07:57

I needed to get absolute paths from relative paths. Below is the function I came up with (after I couldn't find a working one before I gave up and just made one). Works for v1 as well.

Feedback welcomed.

Code: Select all

abs_path(rel_path) {
	return_path := A_WorkingDir "\"
	count := StrSplit(rel_path,"..\")
	loop count.length()-1
		return_path := SubStr(return_path,1,InStr(return_path,"\",,-2))
	rel_path := StrReplace(rel_path,"..\")
	rel_path := StrReplace(rel_path,".\")
	return return_path rel_path
}

Code: Select all

/* example: 
File := ".\Media\Tada.wav"
msgbox abs_path(file)
*/
lexikos
Posts: 9592
Joined: 30 Sep 2013, 04:07
Contact:

Re: Get Absolute path from relative path

23 Aug 2019, 20:54

There is a standard API for this.

Code: Select all

GetFullPathName(path) {
    cc := DllCall("GetFullPathName", "str", path, "uint", 0, "ptr", 0, "ptr", 0, "uint")
    VarSetCapacity(buf, cc*(A_IsUnicode?2:1))
    DllCall("GetFullPathName", "str", path, "uint", cc, "str", buf, "ptr", 0, "uint")
    return buf
}
Or using BufferAlloc (v2 only):

Code: Select all

GetFullPathName(path) {
    cc := DllCall("GetFullPathNameW", "str", path, "uint", 0, "ptr", 0, "ptr", 0, "uint")
    buf := BufferAlloc(cc*2)
    DllCall("GetFullPathNameW", "str", path, "uint", cc, "ptr", buf, "ptr", 0, "uint")
    return StrGet(buf)
}
I often use \folder-in-root-directory.

There's also c:foo, being "foo" in the current working directory for C:. If the actual working directory is on C:, it just uses that, otherwise it uses the value of a strange environment variable, =C:, which is normally only set if the process was launched by cmd.exe. If they aren't set, it ends up being the root directory for that drive. I don't expect it's used much in scripts, but it pays to at least be aware that c:foo is not equivalent to c:\foo, except by chance.

There may be other quirks I'm forgetting.
User avatar
Maestr0
Posts: 136
Joined: 05 Dec 2013, 17:43

Re: Get Absolute path from relative path

24 Aug 2019, 09:06

much appreciated, Lexikos!

Return to “Scripts and Functions (v2)”

Who is online

Users browsing this forum: cimerio, kunkel321, metallizer and 28 guests