Windows API一日一練(83)GetModuleFileName函數
在開發軟體的過程裡,經常需要把資料儲存到當前執行檔案路徑下面,或者讀取當前執行檔案路徑下的一些配置資訊。這時就需要從當前模組裡擷取所在的目錄路徑,以便進行固定的位置操作檔案。要解決這個需求,就需要調用API函數GetModuleFileName來擷取模組所在的路徑。
函數GetModuleFileName聲明如下:
WINBASEAPI
DWORD
WINAPI
GetModuleFileNameA(
__in_opt HMODULE hModule,
__out_ecount_part(nSize, return + 1) LPCH lpFilename,
__in DWORD nSize
);
WINBASEAPI
DWORD
WINAPI
GetModuleFileNameW(
__in_opt HMODULE hModule,
__out_ecount_part(nSize, return + 1) LPWCH lpFilename,
__in DWORD nSize
);
#ifdef UNICODE
#define GetModuleFileName GetModuleFileNameW
#else
#define GetModuleFileName GetModuleFileNameA
#endif // !UNICODE
hModule是模組的控制代碼,或者設定為NULL表示當前模組。
lpFilename是儲存路徑的緩衝區。
nSize是緩衝區的大小。
調用函數的例子如下:
#001 //擷取當前程式所在路徑。
#002 //蔡軍生 2007/12/05 QQ:9073204 深圳
#003 void TestGetExePath(void)
#004 {
#005 //
#006 const int nBufSize = 512;
#007 TCHAR chBuf[nBufSize];
#008 ZeroMemory(chBuf,nBufSize);
#009
#010 //擷取當前執行檔案的路徑。
#011 if (GetModuleFileName(NULL,chBuf,nBufSize))
#012 {
#013 //輸出帶檔案名稱路徑。
#014 OutputDebugString(chBuf);
#015 OutputDebugString(_T("/r/n"));
#016
#017 //擷取檔案路徑。
#018 TCHAR* lpStrPath = chBuf;
#019 PathRemoveFileSpec(lpStrPath);
#020 OutputDebugString(lpStrPath);
#021 OutputDebugString(_T("/r/n"));
#022 }
#023
#024 }
輸出的結果如下:
g:/work/windows_api/wincpp2/debug/WinCpp.exe
g:/work/windows_api/wincpp2/debug