Windows API一日一練(83)GetModuleFileName函數

來源:互聯網
上載者:User
  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

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.