Skip to content

Instantly share code, notes, and snippets.

@myfreeer
Created November 10, 2018 04:11
Show Gist options
  • Save myfreeer/3c2c8b236b0e2149890f330c15f0f721 to your computer and use it in GitHub Desktop.
Save myfreeer/3c2c8b236b0e2149890f330c15f0f721 to your computer and use it in GitHub Desktop.
#include <windows.h>
/**
* GetModulePathW
* 获取当前程序可执行文件所在路径
* @param {WCHAR *} pDirBuf - destination buffer
* @param {DWORD} bufSize - size of buffer
* @return {DWORD} length of module path, 0 for failure
*/
DWORD WINAPI GetModulePathW(WCHAR *pDirBuf, DWORD bufSize) {
WCHAR *szEnd = NULL;
GetModuleFileNameW(NULL, pDirBuf, bufSize);
szEnd = wcsrchr(pDirBuf, L'\\');
if (szEnd) {
*(szEnd) = 0;
return szEnd - pDirBuf;
}
return 0;
}
// get file name without path of module
// 获取当前程序可执行文件名(不包含路径)
DWORD GetModuleNameW(LPWSTR lpFileName, DWORD nSize) {
DWORD ret = GetModuleFileNameW(NULL, lpFileName, nSize);
if (ret == 0) return ret;
WCHAR *szDirEnd = wcsrchr(lpFileName, L'\\');
if (!szDirEnd) return 0;
WCHAR *szFileExt = wcsrchr(szDirEnd, L'.');
if (szFileExt) {
if (wcsncpy_s(lpFileName, nSize, szDirEnd + 1,
szFileExt - szDirEnd - 1) == 0) {
return szFileExt - szDirEnd - 1;
}
} else {
if (wcscpy_s(lpFileName, nSize, szDirEnd + 1) == 0) {
return ret + lpFileName - szDirEnd - 1;
}
}
return 0;
}
// get path to file with the same path of module
// 获取当前程序可执行文件名相同路径,指定文件名文件的路径
BOOL GetModulePathFileW(LPWSTR pDirBuf, LPCWSTR lpFileName, DWORD bufSize) {
WCHAR *szEnd = NULL;
GetModuleFileNameW(NULL, pDirBuf, bufSize);
szEnd = wcsrchr(pDirBuf, L'\\');
if (szEnd) {
++szEnd;
return wcscpy_s(szEnd, bufSize + pDirBuf - szEnd, lpFileName) == 0;
}
return FALSE;
}
// get path to file with the same path and name of module, with different extension
// 获取当前程序可执行文件名相同路径,相同文件名,指定扩展名文件的路径
BOOL GetModuleNameExtW(LPWSTR lpFileName, LPCWSTR lpExt, DWORD nSize) {
DWORD ret = GetModuleFileNameW(NULL, lpFileName, nSize);
if (ret == 0) return ret;
WCHAR *szDirEnd = wcsrchr(lpFileName, L'\\');
if (!szDirEnd) return 0;
WCHAR *szFileExt = wcsrchr(szDirEnd, L'.');
if (szFileExt) {
return wcscpy_s(szFileExt, nSize + lpFileName - szFileExt, lpExt) == 0;
} else {
return wcscat_s(lpFileName, nSize, lpExt) == 0;
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment