VC 獲 取 當前程式執行路徑的幾種方法
1.使用APi函式GetModuleFileName
char path[MAX_PATH];
GetModuleFileName(NULL, path, MAX_PATH); //獲取到完整路徑如:E:\Tools\qq.exe
*strrchr(path,'\\') = '\0'; //擷取路徑E:\Tools
2.MFC
char path[MAX_PATH];
memcpy(path, AfxGetApp()->m_pszHelpFilePath, MAX_PATH) //獲取到完整路徑如:E:\Tools\qq.hlp
*strrchr(path,'\\') = '\0'; //擷取路徑E:\Tools
3 用這個函式也可以做到擷取路徑
PathRemoveFileSpec(LPTSTR pszPath)
例:
LPTSTR GetProgramDir(int nBufferLength, LPTSTR lpBuffer)
{
DWORD dwReturn = 0;
LPTSTR tszSlash;
if (nBufferLength <= 0 || lpBuffer == NULL)
return NULL;
dwReturn = ::GetModuleFileName(NULL, lpBuffer, nBufferLength);
if (dwReturn <= nBufferLength)
{
PathRemoveFileSpec(lpBuffer);
tszSlash = lpBuffer;
}
return tszSlash;
}
2..
string GetPPath() //取程式執行的當前路徑
{
TCHAR exeFullPath[MAX_PATH]; // MAX_PATH
GetModuleFileName(NULL,exeFullPath,MAX_PATH);//得到程式模組名稱,全路徑
char drive[_MAX_DRIVE];
char dir[_MAX_DIR];
_splitpath(exeFullPath, drive, dir, NULL,NULL);
string PragramPath(drive);
string TempPath(dir);
PragramPath += TempPath ;
cout<< PragramPath<<endl;
return PragramPath;
}
3.unicode 工程
TCHAR AppPath[256] = {0};
char g_strAppPath[256] = {0};
::GetModuleFileName(NULL,AppPath, MAX_PATH);
WideCharToMultiByte(CP_ACP, 0, (LPCWSTR)AppPath, -1, g_strAppPath, 256, 0, 0);
*strrchr(g_strAppPath,'\\') = '\0';