-
Notifications
You must be signed in to change notification settings - Fork 1
/
enviroment_variables.c
98 lines (89 loc) · 1.56 KB
/
enviroment_variables.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
#include "shell.h"
/**
* cpyEnviron - This function copies enviroment variables from environ
* to a dynamically allocated array
*/
void cpyEnviron(void)
{
int i = 0, len;
while (environ[i])
i++;
len = i + 2;
enviroment = malloc(sizeof(char *) * len);
enviroment[0] = NULL;
for (i = 0; environ[i]; i++)
{
len = _strlen(environ[i]) + 2;
enviroment[i] = malloc(sizeof(char) * len);
if (!enviroment)
{
perror("failed to allocate memory");
exit(98);
}
enviroment[i][0] = '\0';
enviroment[i] = _strcpy(enviroment[i], environ[i]);
}
enviroment[i] = NULL;
}
/**
* print_env - This function prints enviroment variables
*/
void print_env(void)
{
int i;
for (i = 0; enviroment[i]; i++)
_printf("%s\n", enviroment[i]);
}
/**
* _setenv - This function changes or adds an environment variable
* @argv: Arguments
*/
void _setenv(char **argv)
{
int i = 0;
if (!argv[1] || argv[1][0] == '\0')
{
return;
}
if (!argv[2])
{
perror("value required");
return;
}
while (argv[1][i])
{
if (argv[1][i] == '=')
{
perror("variable name can't contain =");
return;
}
i++;
}
i = find_var(argv[1], enviroment);
if (i == -1)
creat_var(argv);
else
modify_var(argv, i);
}
/**
* _unsetenv - This function removes
* @argv: Arguments
*/
void _unsetenv(char **argv)
{
int i;
int index;
if (!argv[1] || argv[1][0] == '\0')
{
return;
}
index = find_var(argv[1], enviroment);
if (index == -1)
{
return;
}
free(enviroment[index]);
for (i = index; enviroment[i]; i++)
enviroment[i] = enviroment[i + 1];
enviroment[i] = NULL;
}