-
Notifications
You must be signed in to change notification settings - Fork 0
/
environ.c
80 lines (67 loc) · 1.48 KB
/
environ.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
/*
* File: environ.c
* Auth: Carol Waithaka and Daniel Musau
*/
#include "shell.h"
char **_copyenv(void);
void free_env(void);
char **_getenv(const char *var);
/**
* _copyenv - Creates a copy of the environment.
*
* Return: If an error occurs - NULL.
* O/w - a double pointer to the new copy.
*/
char **_copyenv(void)
{
char **new_environ;
size_t size;
int index;
for (size = 0; environ[size]; size++)
;
new_environ = malloc(sizeof(char *) * (size + 1));
if (!new_environ)
return (NULL);
for (index = 0; environ[index]; index++)
{
new_environ[index] = malloc(_strlen(environ[index]) + 1);
if (!new_environ[index])
{
for (index--; index >= 0; index--)
free(new_environ[index]);
free(new_environ);
return (NULL);
}
_strcpy(new_environ[index], environ[index]);
}
new_environ[index] = NULL;
return (new_environ);
}
/**
* free_env - Frees the the environment copy.
*/
void free_env(void)
{
int index;
for (index = 0; environ[index]; index++)
free(environ[index]);
free(environ);
}
/**
* _getenv - Gets an environmental variable from the PATH.
* @var: The name of the environmental variable to get.
*
* Return: If the environmental variable does not exist - NULL.
* Otherwise - a pointer to the environmental variable.
*/
char **_getenv(const char *var)
{
int index, len;
len = _strlen(var);
for (index = 0; environ[index]; index++)
{
if (_strncmp(var, environ[index], len) == 0)
return (&environ[index]);
}
return (NULL);
}