Repository navigation
Expand file tree
/
Copy pathconfig-filename.cpp
More file actions
80 lines (73 loc) · 2.01 KB
/
Copy pathconfig-filename.cpp
File metadata and controls
80 lines (73 loc) · 2.01 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
#include <sys/types.h>
#ifdef _MSC_VER
#include "Userenv.h"
#else
#include <pwd.h>
#include <unistd.h>
#include <dlfcn.h>
#include <climits>
#endif
#include "config-filename.h"
#include "file-helper.h"
#if defined(_MSC_VER) || defined(__MINGW32__)
std::string getDefaultConfigFileName(
const char *programPath,
const std::string &filename
)
{
// try to get in the current directory
if (file::fileExists(filename))
return filename;
std::string r = filename;
// Need a process with query permission set
HANDLE hToken = 0;
if (OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &hToken))
{
// Returns a path like C:/Documents and Settings/nibu if my user name is nibu
char homedir[MAX_PATH];
DWORD size = sizeof(homedir);
if (GetUserProfileDirectoryA(hToken, homedir, &size) && (size > 0)) {
r = std::string(homedir, size - 1).append("\\").append(filename);
}
CloseHandle(hToken);
}
return r;
}
#else
/**
* https://stackoverflow.com/questions/2910377/get-home-directory-in-linux-c
*/
std::string getDefaultConfigFileName(
const char *programPath,
const std::string &filename
)
{
// try to get in the current directory
if (filel::fileExists(filename))
return filename;
// try to get in the /etc directory
std::string r("/etc/" + filename);
if (filel::fileExists(r))
return r;
// try to get in the $HOME directory
struct passwd *pw = getpwuid(getuid());
const char *homedir = pw->pw_dir;
r = std::string(homedir) + "/" + filename;
if (filel::fileExists(r))
return r ;
// try executable file folder
if (programPath) {
std::string p = programPath;
size_t last_slash_idx = p.rfind('/');
if (last_slash_idx == std::string::npos)
last_slash_idx = p.rfind('\\');
if (last_slash_idx != std::string::npos) {
r = p.substr(0, last_slash_idx + 1) + filename;
if (filel::fileExists(r)) {
return r;
}
}
}
return filename;
}
#endif