C++获取运行exe路径和名称

第一种方案

int main(int argc,char* argv[]){
    cout << "path: " << argv[0] << endl;
    char exeName[MAX_PATH] = "";
    char *buf = NULL;
    char *line = strtok_s(argv[0],"\\",&buf);
    while (NULL != line){
        strcpy_s(exeName, line);
        line = strtok_s(NULL,"\\",&buf);
    }
    cout << "exe name: " << exeName << endl;
    return 0;
}

第二种方案

PathUtil.h

#ifndef TEST_PATHUTIL_H
#define TEST_PATHUTIL_H

#include "iostream"
#include <libloaderapi.h>

using namespace std;
/**
 * 路径工具类
 * @author lhDream
 * @Date 2022-7-30 22:26:26
 */
class PathUtil{
    public:
        PathUtil();
        // 获取当前文件路径
        string getPath();
        // 获取当前文件名称
        string getFilename();
    private:
        string path = "";
        string fileName = "";
};
#endif //TEST_PATHUTIL_H

PathUtil.cpp

#include "PathUtil.h"

/**
 * 构造函数
 */
PathUtil::PathUtil(){
    //获取应用程序目录 D:\testPath\test.exe
    char absolutePath[MAX_PATH];
    memset(absolutePath,0,MAX_PATH);
    GetModuleFileNameA(NULL,absolutePath,MAX_PATH);
    path = (absolutePath);

    // 获取应用程序名称 test.exe
    char exeName[MAX_PATH] = "";
    char *buf = NULL;
    char* line = strtok_s(absolutePath,"\\",&buf);
    while (NULL != line){
        strcpy_s(exeName, line);
        line = strtok_s(NULL,"\\",&buf);
    }
    fileName = exeName;
}

/**
 * 获取文件路径
 * @return D:\testPath\test.exe
 */
string PathUtil::getPath(){
    return path;
}
/**
 * 获取文件名称
 * @return test.exe
 */
string PathUtil::getFilename(){
    return fileName;
}