Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find the full path of the C++ Linux program from within?

Tags:

c++

linux

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.

like image 978
Sharath Avatar asked Aug 13 '11 16:08

Sharath


People also ask

How do I find the path of a directory in Linux?

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.

How do you find the entire path in Unix?

The pwd command displays the full, absolute path of the current, or working, directory.

What is absolute path in C?

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.


3 Answers

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.

like image 154
Kerrek SB Avatar answered Oct 21 '22 21:10

Kerrek SB


The top answer to this question lists techniques for a whole bunch of OSes.

like image 37
olooney Avatar answered Oct 21 '22 19:10

olooney


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 );
}
like image 6
MetallicPriest Avatar answered Oct 21 '22 21:10

MetallicPriest