-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.c
107 lines (102 loc) · 8.23 KB
/
main.c
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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
#include <stdlib.h>
#include <windows.h>
#include <stdio.h>
#include <assert.h>
#include <stdint.h>
#include <string.h>
#pragma comment(lib, "Advapi32.lib")
#if LOG
#define add_tp_path_log(...) wprintf(__VA_ARGS__)
#else
#define add_to_path_log(...)
#endif
#ifdef __TINYC__
typedef long LSTATUS;
#define wcscat_s(a, b, c) wcscat(a, c)
#endif
typedef enum {
ATP_FailedToSetRegistryKey,
ATP_FailedToOpenRegistryKey,
ATP_PathKeyNotExisting,
ATP_Ok,
} AddToPathErr;
AddToPathErr add_to_path(const wchar_t* input_path) {
wchar_t path[32*1024] = {'%', 'P', 'A', 'T', 'H', '%', ';'};
wcscat_s(path, 16*1024, input_path);
HKEY key_handle = 0;
DWORD disposition = 0;
LSTATUS status = RegCreateKeyExW(
HKEY_CURRENT_USER,
L"Environment",
0,
NULL,
REG_OPTION_NON_VOLATILE,
KEY_ALL_ACCESS,
NULL,
&key_handle,
&disposition
);
if (status != ERROR_SUCCESS) {
return ATP_FailedToOpenRegistryKey;
}
if (disposition != REG_OPENED_EXISTING_KEY) {
return ATP_PathKeyNotExisting;
}
add_to_path_log(L"path \"%s\"\n", path);
wchar_t path_expanded[32 *1024] = {0};
ExpandEnvironmentStringsW(
path,
path_expanded,
32*1024
);
add_to_path_log(L"path expanded %s\n", path_expanded);
LSTATUS status2 = RegSetValueExW(
key_handle,
L"Path", //Automatically null terminated
0,
REG_EXPAND_SZ,
(BYTE*) path_expanded,
(DWORD)(2*wcslen(path_expanded) + 1)
);
if (status2 == ERROR_SUCCESS) {
return ATP_Ok;
} else {
return ATP_FailedToSetRegistryKey;
}
}
#ifdef __GNUC__
int main(int _argc, char** _argv) {
(void) _argc; (void) _argv;
int argc = 0;
wchar_t ** argv = CommandLineToArgvW(GetCommandLineW(), &argc);
#else
int wmain(int argc, wchar_t** argv) {
#endif
if (argc == 2) {
wchar_t path[MAX_PATH];
if(GetFullPathNameW(argv[1], MAX_PATH, path, NULL) == 0) {
printf("Failed to obtain full path");
exit(-1);
}
AddToPathErr err = add_to_path(path);
if (err == ATP_Ok) {
printf("Added Directory to path\n");
}
else if(err == ATP_FailedToOpenRegistryKey) {
printf("Failed to open registry key\n");
}
else if(err == ATP_FailedToSetRegistryKey) {
printf("Failed to set registry key\n");
}
else if (err == ATP_PathKeyNotExisting) {
printf("Path Key does not exist\n");
}
else {
printf("Unknown error");
assert(0);
}
} else {
printf("Usage: addtopath <dirname>");
}
return 0;
}