C/MFC如何獲得應用程式當前路徑(整理)
阿新 • • 發佈:2019-02-07
第一種方法:
DWORD GetCurrentDirectory(
DWORD nBufferLength, // size, in characters, of directory buffer
LPTSTR lpBuffer // pointer to buffer for current directory
);
BOOL SetCurrentDirectory(
LPCTSTR lpPathName // pointer to name of new current directory
);
第二種方法 用GetModuleFileName得到應用程式的檔名(第一個引數為NULL)
再用_splitpath分析檔名得到路徑 例如: //得到當前路徑
/*char buf[100];
GetCurrentDirectory(sizeof(buf),buf);
MessageBox(buf);
HINSTANCE hInst=NULL;
hInst=AfxGetApp()->m_hInstance;
char path_buffer[_MAX_PATH];
GetModuleFileName(hInst,path_buffer,sizeof(path_buffer));//得到exe檔案的全路徑
//分離路徑和檔名。
char drive[_MAX_DRIVE];
char dir[_MAX_DIR];
char fname[_MAX_FNAME];
char ext[_MAX_EXT];
_splitpath( path_buffer, drive, dir, fname, ext );
CString Path;
Path.Format("%s%s",drive,dir); char path[300]; strcpy(path,drive);
strcat(path,dir); 又或: TCHAR exeFullPath[MAX_PATH];CString strPath;GetModuleFileName(NULL,exeFullPath,MAX_PATH);strPath=(CString)exeFullPath;int position=strPath.ReverseFind('\\');strPath=strPath.Left(position+1);
GetSystemDirectory(buf,100);
MessageBox(buf);
DWORD nBufferLength, // size, in characters, of directory buffer
LPTSTR lpBuffer // pointer to buffer for current directory
);
BOOL SetCurrentDirectory(
LPCTSTR lpPathName // pointer to name of new current directory
);
第二種方法 用GetModuleFileName得到應用程式的檔名(第一個引數為NULL)
再用_splitpath分析檔名得到路徑 例如: //得到當前路徑
/*char buf[100];
GetCurrentDirectory(sizeof(buf),buf);
MessageBox(buf);
HINSTANCE hInst=NULL;
hInst=AfxGetApp()->m_hInstance;
char path_buffer[_MAX_PATH];
GetModuleFileName(hInst,path_buffer,sizeof(path_buffer));//得到exe檔案的全路徑
//分離路徑和檔名。
char drive[_MAX_DRIVE];
char dir[_MAX_DIR];
char fname[_MAX_FNAME];
char ext[_MAX_EXT];
_splitpath( path_buffer, drive, dir, fname, ext );
CString Path;
Path.Format("%s%s",drive,dir); char path[300]; strcpy(path,drive);
strcat(path,dir); 又或: TCHAR exeFullPath[MAX_PATH];CString strPath;GetModuleFileName(NULL,exeFullPath,MAX_PATH);strPath=(CString)exeFullPath;int position=strPath.ReverseFind('\\');strPath=strPath.Left(position+1);
TCHAR FilePath[MAX_PATH];GetModuleFileName(NULL,FilePath,MAX_PATH);(_tcsrchr(FilePath,'\\'))[1] = 0;lstrcat(FilePath,_T("MY.ini"));
GetSystemDirectory(buf,100);
MessageBox(buf);