方法一:__targv
控制台程序:
int _tmain(int argc, TCHAR* argv[], TCHAR* envp[]){ CString strPath = argv[0];}
控制台程序和window程序通用(推荐使用):
CString str(__targv[0]);
注意: 该方法得到路径可能是相对路径,需要转换后获得绝对路径
方法二:_tpgmptr
CString strPath(_tpgmptr);
该方法,编译时会出现警告:
warning C4996: '_wpgmptr': This function or variable may be unsafe. Consider using _get_wpgmptr instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS. See online help for details.
可以通过在工程中添加预定义宏 _CRT_SECURE_NO_WARNINGS 方式去除警告,建议写成如下形式:
TCHAR* szPath = NULL;#ifdef UNICODE_get_wpgmptr(&szPath);#else_get_pgmptr(&szPath);#endifCString strPath(szPath);
方法三:GetModuleFileName
CString strPath;DWORD nSize = GetModuleFileName( NULL,strPath.GetBuffer(MAX_PATH),MAX_PATH);strPath.ReleaseBuffer();
其它获得系统常用路径的方法:
1.获得当前路径
DWORD dwSize = GetCurrentDirectory(0,NULL);CString strPath;GetCurrentDirectory(dwSize,strPath.GetBuffer(dwSize));strPath.ReleaseBuffer();
2.获得临时文件夹路径
DWORD dwSize = GetTempPath(0,NULL);CString strPath;dwSize = GetTempPath(dwSize,strPath.GetBuffer(dwSize));strPath.ReleaseBuffer();
3.获得WINDOWS和system32路径
DWORD dwSize;CString strPath;dwSize = GetWindowsDirectory(NULL,0);dwSize = GetWindowsDirectory(strPath.GetBuffer(dwSize),dwSize);strPath.ReleaseBuffer();dwSize = GetSystemDirectory(NULL,0);dwSize = GetSystemDirectory(strPath.GetBuffer(dwSize),dwSize);strPath.ReleaseBuffer();
4.推荐使用Shell库中函数
TCHAR szPath[MAX_PATH];int CSIDL[] = { CSIDL_WINDOWS, //WINDOWS目录 CSIDL_FONTS, //字体目录 CSIDL_SYSTEM, //SYSTEM32目录 CSIDL_SYSTEMX86, CSIDL_PROGRAM_FILES,//Program Files目录 CSIDL_PROGRAM_FILESX86, CSIDL_PROGRAM_FILES_COMMON, CSIDL_PROFILE, CSIDL_COMMON_FAVORITES, CSIDL_FAVORITES, //用户收藏夹 CSIDL_DESKTOP, //用户桌面目录 CSIDL_MYDOCUMENTS, //我的文档目录 = CSIDL_PERSONAL CSIDL_MYPICTURES, CSIDL_MYMUSIC, CSIDL_MYVIDEO, CSIDL_APPDATA, //用户AppData\Roaming CSIDL_COOKIES, CSIDL_TEMPLATES, CSIDL_RECENT, CSIDL_SENDTO, CSIDL_STARTMENU, CSIDL_PROGRAMS, CSIDL_ADMINTOOLS, CSIDL_STARTUP, CSIDL_LOCAL_APPDATA, CSIDL_INTERNET_CACHE, CSIDL_HISTORY, CSIDL_CDBURN_AREA, CSIDL_COMMON_DESKTOPDIRECTORY, CSIDL_COMMON_DOCUMENTS, CSIDL_COMMON_PICTURES, CSIDL_COMMON_MUSIC, CSIDL_COMMON_VIDEO, CSIDL_COMMON_APPDATA, CSIDL_COMMON_STARTMENU, CSIDL_COMMON_PROGRAMS, CSIDL_COMMON_ADMINTOOLS, CSIDL_COMMON_STARTUP, CSIDL_COMMON_TEMPLATES,};for (int i=0 ; i < _countof(CSIDL); i++) { if(SUCCEEDED(SHGetFolderPath(NULL, CSIDL[i], NULL, SHGFP_TYPE_CURRENT, szPath))) _tprintf(_T("%d, %s\n"), i, szPath); if(SUCCEEDED(SHGetFolderPath(NULL, CSIDL[i], NULL, SHGFP_TYPE_DEFAULT, szPath))) _tprintf(_T("%d, %s\n"), i, szPath);}