Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

filenames

I want to get the full path of the current process.

I use _getcwd to get the current working directory. But it not includes file name.

How can I get file name like: filename.exe?

like image 725
Phat Tran Avatar asked Sep 03 '12 23:09

Phat Tran


2 Answers

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
}
like image 128
Seçkin Savaşçı Avatar answered Oct 11 '22 03:10

Seçkin Savaşçı


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.

like image 25
marcinj Avatar answered Oct 11 '22 02:10

marcinj