How to Get the Filename of the Currently Running Executable in C++

argv[0] of your main function is your filename.

A simple code snippet:

#include<stdio.h>
int main(int argc, char** argv)
{
    //access argv[0] here
}

If you cannot access/change code in main(), you can do something like this:

std::string executable_name()
{
#if defined(PLATFORM_POSIX) || defined(__linux__) //check defines for your setup

    std::string sp;
    std::ifstream("/proc/self/comm") >> sp;
    return sp;

#elif defined(_WIN32)

    char buf[MAX_PATH];
    GetModuleFileNameA(nullptr, buf, MAX_PATH);
    return buf;

#else

    static_assert(false, "unrecognized platform");

#endif
}

On windows you can use:

TCHAR szExeFileName[MAX_PATH]; 
GetModuleFileName(NULL, szExeFileName, MAX_PATH);

szExeFileName will contain full path + executable name

[edit]

For more portable solution use argv[0] or some other platform specific code. You can find such aproach here: https://github.com/mirror/boost/blob/master/libs/log/src/process_name.cpp.


On Linux, the filename of your binary is the destination of a symlink at /proc/self/exe. You can use the readlink system call to find the destination of a symlink.

Note that this tells you the actual location on disk where the binary is stored, not simply the command the user used to start your program.

Tags:

C++

Filenames