PathUtils.hpp
1.79 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
#ifndef _PATH_UTILS_H_
#define _PATH_UTILS_H_
#include <string>
#if defined(WIN32) || defined(_WIN32) || defined(__WIN32__) || defined(__NT__)
#include<Windows.h>
#elif defined(linux) || defined(__linux)
#include <string.h>
#include <unistd.h>
#include <dlfcn.h>
#include <limits.h>
#include <iostream>
#endif // WINDOWS
namespace helpers
{
namespace PathUtils {
#if defined(WIN32) || defined(_WIN32) || defined(__WIN32__) || defined(__NT__)
static HMODULE GetSelfModuleHandle()
{
MEMORY_BASIC_INFORMATION mbi;
return (
(::VirtualQuery(GetSelfModuleHandle, &mbi, sizeof(mbi)) != 0)
? (HMODULE)mbi.AllocationBase : NULL
);
}
static std::string GetCurrentProgramDir()
{
std::string strCurrentPath = "";
char curDirector[260] = { 0 };
GetModuleFileName(GetSelfModuleHandle(), curDirector, 260);
strCurrentPath = curDirector;
size_t nameStart = strCurrentPath.rfind("\\");
strCurrentPath = strCurrentPath.substr(0, nameStart + 1);
return strCurrentPath;
}
#elif defined(linux) || defined(__linux)
static std::string GetCurrentProgramDir()
{
std::string strCurrentPath = "";
char szCurWorkPath[256];
memset(szCurWorkPath, '\0', 256);
int nRet = readlink("/proc/self/exe", szCurWorkPath, 256);
if (nRet > 256 || nRet < 0)
{
return strCurrentPath;
}
for (int i = nRet; i > 0; i--)
{
if (szCurWorkPath[i] == '/' || szCurWorkPath[i] == '\\')
{
szCurWorkPath[i] = '\0';
break;
}
}
strCurrentPath = szCurWorkPath;
return strCurrentPath;
}
static std::string GetCmdDir() {
char cwd[PATH_MAX];
if (getcwd(cwd, sizeof(cwd)) != nullptr) {
std::cout << "当前工作目录是: " << cwd << std::endl;
} else {
std::cerr << "错误: 无法获取当前工作目录。" << std::endl;
}
return cwd;
}
#endif
}
}
#endif // !_PATH_UTILS_H_