-
Notifications
You must be signed in to change notification settings - Fork 0
/
env.c
138 lines (126 loc) · 2.35 KB
/
env.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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
#include "shellhead.h"
/**
* penv - prints environ
*/
void penv(void)
{
int i = 0;
while (environ[i])
{
write(STDOUT_FILENO, environ[i], _strlen(environ[i]));
write(STDOUT_FILENO, "\n", 1);
i++;
}
}
/**
* _getenv - gets environment value
* @name: name of enviornment variable
* Return: pointer to value of variable
*/
char *_getenv(const char *name)
{
int i = 0;
char *var = NULL, *val = NULL, *ptr;
while (environ[i] != NULL)
{
var = _strdup(environ[i]);
ptr = _strtok(var, "=");/** separate var name from var value */
if (_strcmp(ptr, name) == 0)
{ /** var name found, return only var value */
ptr = _strtok(NULL, "=");
val = _strdup(ptr);
free(var);
return (val);
}
free(var); /** name not found */
i++;
}
return (NULL);
}
/**
* _setenv - sets environment variable
* @name: name of variable
* @value: value of variable
* @overwrite: overwrite value to make changes
* Return: 0 for success or -1 on failure
*/
int _setenv(const char *name, const char *value, int overwrite)
{
int i = 0, j = 0;
char *var, *var2, *cpy;
if (name == NULL || _strlen(name) == 0)
return (-1);
if (value == NULL)
value = "";
cpy = _strdup(name);
_strcat(cpy, "="), _strcat(cpy, value);
while (name[j])
{
if (name[j] == '=')
{
free(cpy);
return (-1);
}
j++;
}
while (environ[i] != NULL)
{
var = _strdup(environ[i]);
var2 = _strtok(var, "=");
if ((_strcmp(var2, name) == 0) && (overwrite > 0))
{
environ[i] = _strdup(cpy);
free(var), free(cpy);
return (0);
}
else if ((_strcmp(var2, name) == 0) && (overwrite == 0))
{
free(var), free(cpy);
return (0);
}
i++;
}
environ[i++] = _strdup(cpy);
environ[i] = NULL;
free(var), free(cpy);
return (0);
}
/**
* _unsetenv - unsets environment variable
* @name: name of variable
* Return: 0 for success or -1 on failure
*/
int _unsetenv(const char *name)
{
int i = 0, j = 0;
char *var, *var2, *cpy;
if (name == NULL)
return (-1);
if (_strlen(name) == 0)
return (-1);
while (name[j])
{
if (name[j] == '=')
return (-1);
j++;
}
while (environ[i] != NULL)
{
var = _strdup(environ[i]);
var2 = _strtok(var, "=");
if ((_strcmp(var2, name) == 0))
{
cpy = environ[i];
while (environ[i] != NULL)
{
environ[i] = environ[i + 1];
i++;
}
free(var), free(cpy);
return (0);
}
i++;
}
free(var);
return (0);
}