-
Notifications
You must be signed in to change notification settings - Fork 2
/
loadenv.c
112 lines (107 loc) · 2.56 KB
/
loadenv.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
108
109
110
111
112
#include "types.h"
#include "stat.h"
#include "user.h"
#include "fs.h"
#define defaultEnv "ENV"
// NOTHING - READ$ - LOADING_NAME - READ CH TO NAME- READ$ - LOADED_NAME-
#define LOADING_NAME 0
#define NOTHING 1
#define LOADING_TEXT 2
char buf[512], name[ENV_CONTENT_LEN], text[ENV_CONTENT_LEN];
int fd, n, i, j, state, lenName, lenText, silent;
void set_new_env() {
if (j > 0) {
if (j >= ENV_CONTENT_LEN) {
close(fd);
exit();
}
text[j] = 0;
lenText = j;
if (!silent)
printf(1, " loaded text %s\n", text);
setenv(2, name, (char**)(int)text, 1);
}
j = 0;
}
int main(int argc, char* argv[]) {
fd = -1;
silent = 0;
if (argc == 2 && argv[1][0] == '-' && argv[1][1] == 's') {
silent = 1;
}
if (argc > 1 + silent) {
if (!silent)
printf(1, "Loading file %s...\n", argv[1 + silent]);
fd = open(argv[1 + silent], 0);
if (fd < 0) {
if (!silent)
printf(1, "Load Error!\n");
exit();
}
}
if (fd < 0) {
if (!silent)
printf(1, "Loading file %s...\n", defaultEnv);
fd = open(defaultEnv, 0);
}
if(fd < 0){
if (!silent)
printf(1, "Load Error!\n");
}
else {
j = 0, state = NOTHING;
while(((i=0), n = read(fd, buf, sizeof(buf)))>0) {
while (i < n) {
char temp = buf[i++];
if (temp == '$') {
// just started!
if (state == NOTHING) {
j = 0;
state = LOADING_NAME;
}
// LOADING_NAME
else if (state == LOADING_NAME) {
if (j >= ENV_CONTENT_LEN || j == 0) {
close(fd);
exit();
}
name[j] = 0;
state = LOADING_TEXT;
lenName = j;
j = 0;
if (!silent)
printf(1, "Found ENV_NAME:%s\n", name);
}
// a new env
else if(state == LOADING_TEXT) {
set_new_env();
state = LOADING_NAME;
}
}
else if (temp == ' ' || temp == '\n' || temp == '\r' || temp == '\t') {
if (state == LOADING_TEXT) {
set_new_env();
}
}
else {
if (state == LOADING_NAME) {
name[j++] = temp;
if (j >= ENV_CONTENT_LEN) {
close(fd);
exit();
}
}
else if (state == LOADING_TEXT) {
text[j++] = temp;
if (j >= ENV_CONTENT_LEN) {
close(fd);
exit();
}
}
}
}
}
set_new_env();
}
exit();
}