C++获取当前进程绝对路径

时间:2023-03-08 23:14:36
C++获取当前进程绝对路径

获取进程的绝对路径(代码同时操作字符串获取了文件目录):

第一种代码:

wstring GetProgramDir()
{
TCHAR exeFullPath[MAX_PATH]; // Full path
GetModuleFileName(NULL,exeFullPath,MAX_PATH);
wstring strPath = __TEXT("");
strPath = (wstring)exeFullPath; // Get full path of the file
int pos = strPath.find_last_of(L'\\', strPath.length());
return strPath.substr(0, pos); // Return the directory without the file name
}

第二种代码:

CString sPath;
GetModuleFileNameA(NULL, sPath.GetBufferSetLength(MAX_PATH + ), MAX_PATH);
sPath.ReleaseBuffer();
int nPos=sPath.ReverseFind(_T('\\'));
sPath = sPath.Left(nPos);