控制檯程序:ide
int _tmain(int argc, TCHAR* argv[], TCHAR* envp[]) { CString strPath = argv[0]; }
控制檯程序和window程序通用(推薦使用):函數
CString str(__targv[0]);
注意: 該方法獲得路徑多是相對路徑,須要轉換後得到絕對路徑字體
CString strPath(_tpgmptr);
該方法,編譯時會出現警告:spa
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.code
能夠經過在工程中添加預約義宏 _CRT_SECURE_NO_WARNINGS 方式去除警告,建議寫成以下形式:文檔
TCHAR* szPath = NULL; #ifdef UNICODE _get_wpgmptr(&szPath); #else _get_pgmptr(&szPath); #endif CString strPath(szPath);
CString strPath; DWORD nSize = GetModuleFileName( NULL,strPath.GetBuffer(MAX_PATH),MAX_PATH); strPath.ReleaseBuffer();
DWORD dwSize = GetCurrentDirectory(0,NULL); CString strPath; GetCurrentDirectory(dwSize,strPath.GetBuffer(dwSize)); strPath.ReleaseBuffer();
2.得到臨時文件夾路徑get
DWORD dwSize = GetTempPath(0,NULL); CString strPath; dwSize = GetTempPath(dwSize,strPath.GetBuffer(dwSize)); strPath.ReleaseBuffer();
3.得到WINDOWS和system32路徑io
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); }