I have this requirement where I need to find the full path for the C++ program from within. For Windows, I have the following solution. The argv[0] may or may not contain the full path. But I need to be certain.
TCHAR drive[_MAX_DRIVE], dir[_MAX_DIR], base[_MAX_FNAME], ext[_MAX_EXT];
TCHAR fullPath[255+1];
_splitpath(argv[0],drive,dir,base,ext);
SearchPath(NULL,base,ext,255,fullPath,NULL);
What is the Linux (gcc) equivalent for the above code? Would love to see a portable code.
To determine the exact location of the current directory at a shell prompt and type the command pwd. This example shows that you are in the user sam's directory, which is in the /home/ directory. The command pwd stands for print working directory.
The pwd command displays the full, absolute path of the current, or working, directory.
For example, if your prompt was "C:\Windows>" and you wanted to know the absolute path of a calc.exe file in that directory, its absolute path is "c:\windows\calc.exe". In other words, the absolute path is the full directory path plus the file name.
On Linux (Posix?) you have a symbolic link /proc/self/exe
which links to the full path of the executable.
On Windows, use GetModuleFileName
.
Never rely on argv[0]
, which is not guaranteed to be anything useful.
Note that paths and file systems are not part of the language and thus necessarily a platform-dependent feature.
The top answer to this question lists techniques for a whole bunch of OSes.
string get_path( )
{
char arg1[20];
char exepath[PATH_MAX + 1] = {0};
sprintf( arg1, "/proc/%d/exe", getpid() );
readlink( arg1, exepath, PATH_MAX );
return string( exepath );
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With