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

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, 1024 );
        return string( exepath );
}

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.

Tags:

Linux

C++