c++実行可能プログラムのexe名を取得

1070 ワード

https://github.com/xia-chu/ZLMediaKit/blob/master/src/Common/config.cpp
 
 
string exePath() {
    char buffer[PATH_MAX * 2 + 1] = { 0 };
    int n = -1;
#if defined(_WIN32)
    n = GetModuleFileNameA(NULL, buffer, sizeof(buffer));
#elif defined(__MACH__) || defined(__APPLE__)
    n = sizeof(buffer);
    if (uv_exepath(buffer, &n) != 0) {
        n = -1;
    }
#elif defined(__linux__)
    n = readlink("/proc/self/exe", buffer, sizeof(buffer));
#endif

    string filePath;
    if (n <= 0) {
        filePath = "./";
    }
    else {
        filePath = buffer;
    }

#if defined(_WIN32)
    //windows         unix  ,        unix     
    for (auto &ch : filePath) {
        if (ch == '\\') {
            ch = '/';
        }
    }
#endif //defined(_WIN32)

    return filePath;
}
string exeDir() {
    auto path = exePath();
    return path.substr(0, path.rfind('/') + 1);
}
string exeName() {
    auto path = exePath();
    return path.substr(path.rfind('/') + 1);
}