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';