how to get the current executable directory?

May 29, 2020 at 5:37pm
Hi,

filesystem::current_path() returns current working directory but I need the directory from which the executing program was launched. Is there a way?

Regards,
Juan
May 29, 2020 at 5:47pm
Without having already saved the information prior in the execution of the program, there isn't a cross-platform way I know of.

On Windows, you can use the API call GetModuleFileName.
https://docs.microsoft.com/en-us/windows/win32/api/libloaderapi/nf-libloaderapi-getmodulefilenamea
May 29, 2020 at 5:49pm
Not sure if it works with your compiler, but argv[0] gives the fullname of the app so you can extract the directory.
May 29, 2020 at 6:01pm
argv[0] doesn't always give the full path of the app, it can just give the exe name, e.g. when the application is simply started from the local directory. Also, on some platforms I think you can arbitrarily manipulate what gets put into argv[0], but I'm not too familiar with this.

(Edit: To clarify, it depends on the shell you're using, and not the C++ program itself, as far as I can tell)
Last edited on May 29, 2020 at 6:37pm
May 29, 2020 at 6:49pm
argv[0] will give an arbitrary value set by the environment that doesn't necessarily have anything to do with the path to the current process' executable.
On Windows, GetModuleFileName() is the correct solution. I imagine there are equivalent functions on other platforms.
Last edited on May 29, 2020 at 6:50pm
May 29, 2020 at 7:33pm
Some tools even let you set it on the fly, like ZSH

1
2
3
4
nickchambers@qa ~ % code/arg0
code/arg0
nickchambers@qa ~ % ARGV0=thunderfury code/arg0
thunderfury
May 29, 2020 at 8:10pm
GetModuleFileName works!!
Thanks!!

Juan
Topic archived. No new replies allowed.