1. 程式人生 > >VC++6.0 MFC獲取當前工作路徑和可執行檔案路徑

VC++6.0 MFC獲取當前工作路徑和可執行檔案路徑

1. 獲取Debug或Release所在的路徑  
CString GetModuleDir()   
{   
 HMODULE module = GetModuleHandle(0);   
 char pFileName[MAX_PATH];   
 GetModuleFileName(module, pFileName, MAX_PATH);   
   
 CString csFullPath(pFileName);   
 int nPos = csFullPath.ReverseFind( _T('\\') );   
 if( nPos < 0 )   
  return CString("");   
 else   
  return csFullPath.Left( nPos );   
}  
  
   
  
2. 獲取當前工作路徑(dsp所在路徑)  
  
//獲取工作路徑  
CString GetWorkDir()   
{    
 char pFileName[MAX_PATH];   
 int nPos = GetCurrentDirectory( MAX_PATH, pFileName);   
   
 CString csFullPath(pFileName);    
 if( nPos < 0 )   
  return CString("");   
 else   
  return csFullPath;   
}  

路徑分解函式:

    char a_sFileName[256];     
    GetModuleFileName(NULL,a_sFileName,256);   
    CString sPath;  
  
    CString sDrive;//磁碟名  
    CString sDir;//檔案路徑  
    CString sFileName;//取出檔案路徑後的檔名  
    CString sExt;//副檔名  
  
    char drive[_MAX_DRIVE];//磁碟名  
    char dir[_MAX_DIR];//路徑名  
    char fname[_MAX_FNAME];//檔名  
    char ext[_MAX_EXT];//副檔名  
  
    _splitpath(a_sFileName, drive, dir, fname, ext );  
  
    sDrive.Format("%s",drive);  
    sDir.Format("%s",dir);  
    sFileName.Format("%s",fname);  
    sExt.Format("%s",ext);  
  
    sPath= sDrive + sDir + sFileName + a_sSuffix + sExt;  

    CString strText;
    TCHAR exepath[MAX_PATH]={0};
    ::GetModuleFileName(NULL,exepath,MAX_PATH);
    strText=exepath;
    strText=strText.Left(strText.ReverseFind(''''));
    strText += _T("");

GetModuleFileName是一個API函式,通過這個函式,可以獲得執行的當前程式的EXE檔案所在的路徑。直接將這幾句程式碼,在MFC中封裝成一個函式即可。

GetModuleFileName第一個引數是示例控制代碼,設為NULL則表示當前執行的EXE的。第二個引數就是接受得到的可執行路徑的字串緩衝。第三個是緩衝的大小。大小就是宣告的緩衝的大小,以TCHAR為單位。

strText.Left()是CString提供的字串擷取函式,具體的可以檢視MSDN或者本站其他相關文章。

ReverseFind()是CString提供的字串查詢函式,具體的可以檢視MSDN或者本站其他相關文章。

轉自:https://blog.csdn.net/xjujun/article/details/8054990