TAGS :Viewed: 13 - Published at: a few seconds ago

[ Get the original location where the program is called ]

Is there any way to know the directory where the program is originally spawned in C? I want my program to know where it is located in the computer. I already tried using _getcwd() in direct.h. I also tried getcwd() using unistd.h. But here's the problem. If I added a PATH to my program's directory, the functions _getcwd() and getcwd() path will return the path where I called the program. So if I ran the program in dekstop, it will return the path of the desktop instead. I already tried using this method but it doesn't fix the problem. It returns the value of the calling path. I would like to know what function to use to know the path of the program and not the path that the program is called. What function should I use?

Answer 1


The current working directory is of no use whatsoever. There is no connection between an executable image's location in the filesystem and the current working directory, other than coincidental.

You can retrieve the fully qualified path to the executable by calling _get_wpgmptr (a Microsoft-specific extension to the CRT that ships with Visual Studio) or GetModuleFileName (passing NULL for hModule), and extract the path by calling PathRemoveFileSpec (or PathCchRemoveFileSpec for Windows 8 and above).