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?
Asked
Active
Viewed 356 times
0

Community
- 1
- 1

Bryan James
- 65
- 1
- 11
-
Already tried those method earlier. It's returning the path of where it is called and not the original path of the program being called. – Bryan James May 16 '16 at 13:08
1 Answers
0
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).

IInspectable
- 46,945
- 8
- 85
- 181
-
I'm using Windows 7. What library does `_get_wpgmptr()` appears? Already included `stdlib.h` and `windows.h` but the compiler says: `undefined reference to ' _get_wpgmptr'`. – Bryan James May 16 '16 at 13:28
-
1@BryanJames: `_get_wpgmptr()` is part of Visual Studio's CRT implementation, so you need to `#include
` **and** use Visual Studio (or the Microsoft Compiler). If you are using a different compiler, you can use the Windows API call `GetModuleFileName` instead. – IInspectable May 16 '16 at 13:31