-
Notifications
You must be signed in to change notification settings - Fork 29
/
env2.c
129 lines (117 loc) · 2.44 KB
/
env2.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
#include "holberton.h"
/**
* copy_info - copies info to create
* a new env or alias
* @name: name (env or alias)
* @value: value (env or alias)
*
* Return: new env or alias.
*/
char *copy_info(char *name, char *value)
{
char *new;
int len_name, len_value, len;
len_name = _strlen(name);
len_value = _strlen(value);
len = len_name + len_value + 2;
new = malloc(sizeof(char) * (len));
_strcpy(new, name);
_strcat(new, "=");
_strcat(new, value);
_strcat(new, "\0");
return (new);
}
/**
* set_env - sets an environment variable
*
* @name: name of the environment variable
* @value: value of the environment variable
* @datash: data structure (environ)
* Return: no return
*/
void set_env(char *name, char *value, data_shell *datash)
{
int i;
char *var_env, *name_env;
for (i = 0; datash->_environ[i]; i++)
{
var_env = _strdup(datash->_environ[i]);
name_env = _strtok(var_env, "=");
if (_strcmp(name_env, name) == 0)
{
free(datash->_environ[i]);
datash->_environ[i] = copy_info(name_env, value);
free(var_env);
return;
}
free(var_env);
}
datash->_environ = _reallocdp(datash->_environ, i, sizeof(char *) * (i + 2));
datash->_environ[i] = copy_info(name, value);
datash->_environ[i + 1] = NULL;
}
/**
* _setenv - compares env variables names
* with the name passed.
* @datash: data relevant (env name and env value)
*
* Return: 1 on success.
*/
int _setenv(data_shell *datash)
{
if (datash->args[1] == NULL || datash->args[2] == NULL)
{
get_error(datash, -1);
return (1);
}
set_env(datash->args[1], datash->args[2], datash);
return (1);
}
/**
* _unsetenv - deletes a environment variable
*
* @datash: data relevant (env name)
*
* Return: 1 on success.
*/
int _unsetenv(data_shell *datash)
{
char **realloc_environ;
char *var_env, *name_env;
int i, j, k;
if (datash->args[1] == NULL)
{
get_error(datash, -1);
return (1);
}
k = -1;
for (i = 0; datash->_environ[i]; i++)
{
var_env = _strdup(datash->_environ[i]);
name_env = _strtok(var_env, "=");
if (_strcmp(name_env, datash->args[1]) == 0)
{
k = i;
}
free(var_env);
}
if (k == -1)
{
get_error(datash, -1);
return (1);
}
realloc_environ = malloc(sizeof(char *) * (i));
for (i = j = 0; datash->_environ[i]; i++)
{
if (i != k)
{
realloc_environ[j] = datash->_environ[i];
j++;
}
}
realloc_environ[j] = NULL;
free(datash->_environ[k]);
free(datash->_environ);
datash->_environ = realloc_environ;
return (1);
}