在開發(fā)軟件的過程里,經(jīng)常需要把數(shù)據(jù)保存到當(dāng)前執(zhí)行文件路徑下面,或者讀取當(dāng)前執(zhí)行文件路徑下的一些配置信息。這時就需要從當(dāng)前模塊里獲取所在的目錄路徑,以便進(jìn)行固定的位置操作文件。要解決這個需求,就需要調(diào)用API函數(shù)GetModuleFileName來獲取模塊所在的路徑。
函數(shù)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是模塊的句柄,或者設(shè)置為NULL表示當(dāng)前模塊。
lpFilename是保存路徑的緩沖區(qū)。
nSize是緩沖區(qū)的大小。
調(diào)用函數(shù)的例子如下:
#001 //獲取當(dāng)前程序所在路徑。
#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 //獲取當(dāng)前執(zhí)行文件的路徑。
#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 }
輸出的結(jié)果如下:
g:\work\windows_api\wincpp2\debug\WinCpp.exe
g:\work\windows_api\wincpp2\debug