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;
class PathUtil{
public:
PathUtil();
string getPath();
string getFilename();
private:
string path = "";
string fileName = "";
};
#endif
PathUtil.cpp
#include "PathUtil.h"
PathUtil::PathUtil(){
char absolutePath[MAX_PATH];
memset(absolutePath,0,MAX_PATH);
GetModuleFileNameA(NULL,absolutePath,MAX_PATH);
path = (absolutePath);
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;
}
string PathUtil::getPath(){
return path;
}
string PathUtil::getFilename(){
return fileName;
}