Getting current file path (runtime.Caller)

3,208 views
Skip to first unread message

Dobrosław Żybort

unread,
Feb 22, 2013, 9:57:05 AM2/22/13
to golan...@googlegroups.com
Hello,

I have one problem:
I would like to get current exe file path. I know I can't rely on os.Getwd() because I want to execute my file from different folders without issues.
So I found http://andrewbrookins.com/tech/golang-get-directory-of-the-current-file/

Sample program:
http://play.golang.org/p/lN0NZn__vH

I changed 1 to 0 in runtime.Caller(0) because runtime.Caller(1) returning c:/Go/src/pkg/runtime/proc.c.
go build and everything looked nice, I got file path but... when I moved my exe file it's still showing me same path it was build in:
D:\Golibs\my\src\hello>hello.exe
D:/Golibs/my/src/hello/hello.go

and different path:
D:\Golibs\my\src>hello.exe
D:/Golibs/my/src/hello/hello.go
// still same
Is that expected behaviour?

Is there any cross platform, portable way of getting executable file path? (Not path from with we executing it)

Best regards,
Dobrosław Żybort


Matt Kane's Brain

unread,
Feb 22, 2013, 10:14:34 AM2/22/13
to Dobrosław Żybort, golan...@googlegroups.com
That's the source file path, not the executable path. The executable
name is in os.Args[0]. The path to it is not always absolute, and the
name can change depending how it's started.

--
matt kane's brain
twitter: the_real_mkb / nynexrepublic
http://hydrogenproject.com

Dobrosław Żybort

unread,
Feb 22, 2013, 10:52:03 AM2/22/13
to golan...@googlegroups.com, Dobrosław Żybort
Thank you for reply.

Is there a way to always get absolute file path? Or at last absolute path to folder where file reside?

Best regards,
Dobrosław Żybort

brainman

unread,
Feb 22, 2013, 4:37:22 PM2/22/13
to golan...@googlegroups.com

Matt Kane's Brain

unread,
Feb 22, 2013, 4:47:13 PM2/22/13
to brainman, golan...@googlegroups.com
On Fri, Feb 22, 2013 at 4:37 PM, brainman <alex.b...@gmail.com> wrote:
> http://golang.org/pkg/path/filepath/#Abs ?

That will work if your current working directory is the same as it was
when you started.

If the program was started by looking in the PATH, all you get is
program name, so you can probably try exec.LookPath:
http://golang.org/pkg/os/exec/#LookPath

brainman

unread,
Feb 22, 2013, 6:07:36 PM2/22/13
to golan...@googlegroups.com, brainman

Dobrosław Żybort

unread,
Feb 22, 2013, 7:15:37 PM2/22/13
to golan...@googlegroups.com, brainman
It's working! Thank you very much.

Best regards,
Dobrosław Żybort

W dniu sobota, 23 lutego 2013 00:07:36 UTC+1 użytkownik brainman napisał:
http://godoc.org/bitbucket.org/kardianos/osext ?

Alex
Reply all
Reply to author
Forward
0 new messages