C Tips:获得当前运行目录(Windows版)

来源:互联网 发布:下载盯盯软件 编辑:程序博客网 时间:2024/06/11 00:15

接口:

BOOL GetCurrentModuleFolderPath(_Out_ LPTSTR * lpFolderPath, _Out_ DWORD * pLength);

实现:

#include <windows.h>const TCHAR FolderDelimiter = _T('\\');const TCHAR StringDelimiter = _T('\0');BOOL GetCurrentModuleFolderPath(_Out_ LPTSTR * lpFolderPath, _Out_ DWORD * pLength){static TCHAR fullPath[MAX_PATH];PTSTR delimiter = NULL;size_t size = 0;ZeroMemory(fullPath, MAX_PATH * sizeof(TCHAR));GetModuleFileName(NULL, fullPath, MAX_PATH);if (fullPath[MAX_PATH - 1] != StringDelimiter){goto EXIT_FAIL;}delimiter = _tcsrchr(fullPath, FolderDelimiter);if (!delimiter){goto EXIT_FAIL;}*pLength = delimiter - fullPath;size = (*pLength + 1) * sizeof(TCHAR);*lpFolderPath = (LPTSTR)malloc(size);if (!*lpFolderPath){goto EXIT_FAIL;}ZeroMemory(*lpFolderPath, size);_tcsncpy_s(*lpFolderPath, *pLength + 1, fullPath, *pLength);(*lpFolderPath)[*pLength] = StringDelimiter;return TRUE;EXIT_FAIL:pLength = 0;return FALSE;}

测试:

int _tmain(int argc, _TCHAR* argv[]){LPTSTR path = NULL;DWORD length = 0;if (!GetCurrentModuleFolderPath(&path, &length)){_tprintf(_T("GetCurrentModuleFolderPath() Failed!\n"));}else{_tprintf(_T("Current folder: \n%s\nLength: %d\n"), path, length);}if (path){free(path);path = NULL;}return 0;}

结果:


0 0
原创粉丝点击