-
Notifications
You must be signed in to change notification settings - Fork 0
/
setenv.c
161 lines (140 loc) · 2.39 KB
/
setenv.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
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
#include "shell.h"
/**
* get_env - give the value of global variable
* @glob_v: glob_value of the global var
* Return: string
*/
char *get_env(const char *glob_v)
{
int i, m;
char *valeur;
if (!glob_v)
return (NULL);
for (i = 0; environ[i]; i++)
{
m = 0;
if (glob_v[m] == environ[i][m])
{
while (glob_v[m])
{
if (glob_v[m] != environ[i][m])
break;
m++;
}
if (glob_v[m] == '\0')
{
valeur = (environ[i] + m + 1);
return (valeur);
}
}
}
return (0);
}
/**
* concatenat - concats three strings in new allocation memo
* @glob_v: first string input
* @valeur1: second string input
* @valeur: Third string input
* Return: pointer to the new string
*/
char *concatenat(char *glob_v, char *valeur1, char *valeur)
{
char *result;
int len1, len2, len3, i, w;
len1 = str_len(glob_v);
len2 = str_len(valeur1);
len3 = str_len(valeur);
result = malloc(len1 + len2 + len3 + 1);
if (!result)
return (NULL);
for (i = 0; glob_v[i]; i++)
result[i] = glob_v[i];
w = i;
for (i = 0; valeur1[i]; i++)
result[w + i] = valeur1[i];
w = w + i;
for (i = 0; valeur[i]; i++)
result[w + i] = valeur[i];
w = w + i;
result[w] = '\0';
return (result);
}
/**
* _setenv - Initialize a new environment variable, or modify an existing one
* @arr: array of entered words
*/
void _setenv(char **arr)
{
int i, m, w;
if (!arr[1] || !arr[2])
{
perror(get_env("_"));
return;
}
for (i = 0; environ[i]; i++)
{
m = 0;
if (arr[1][m] == environ[i][m])
{
while (arr[1][m])
{
if (arr[1][m] != environ[i][m])
break;
m++;
}
if (arr[1][m] == '\0')
{
w = 0;
while (arr[2][w])
{
environ[i][m + 1 + w] = arr[2][w];
w++;
}
environ[i][m + 1 + w] = '\0';
return;
}
}
}
if (!environ[i])
{
environ[i] = concatenat(arr[1], "=", arr[2]);
environ[i + 1] = '\0';
}
}
/**
* _unsetenv - Remove an environment variable
* @arr: array of entered words
*/
void _unsetenv(char **arr)
{
int i, m;
if (!arr[1])
{
perror(get_env("_"));
return;
}
for (i = 0; environ[i]; i++)
{
m = 0;
if (arr[1][m] == environ[i][m])
{
while (arr[1][m])
{
if (arr[1][m] != environ[i][m])
break;
m++;
}
if (arr[1][m] == '\0')
{
free(environ[i]);
environ[i] = environ[i + 1];
while (environ[i])
{
environ[i] = environ[i + 1];
i++;
}
return;
}
}
}
}