-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy path_getenv.c
87 lines (80 loc) · 1.84 KB
/
_getenv.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
#include "holberton.h"
/**
* _getenv - gets an environment variable
* @name: environment variable to get
* Return: pointer to environment variable or NULL if there is no match
*/
char *_getenv(const char *name)
{
char **environ_copy;
char *variable, *value, *path;
int compare;
unsigned int path_length, environ_length, length, i;
environ_length = 0;
while (environ[environ_length] != NULL)
environ_length++;
environ_copy = NULL;
environ_copy = copy_env(environ_copy, environ_length);
length = _strlen((char *)name);
i = 0;
while (environ_copy[i] != NULL)
{
variable = environ_copy[i];
compare = _strncmp((char *)name, variable, length);
if (compare == 1)
{
value = strtok(variable, "=");
value = strtok(NULL, "\n ");
if (value == '\0')
{
errors(4);
exit(EXIT_FAILURE);
}
path_length = _strlen(value);
path = malloc(sizeof(char) * path_length + 1);
if (path == NULL)
{
errors(3);
return (NULL);
}
path = _strcpy(path, value);
free_dp(environ_copy, environ_length);
return (path);
}
i++;
}
return (NULL);
}
/**
* copy_env - copies environment variable
* @environ_copy: pointer to copy of environment variable
* @environ_length: length of environment variable
* Return: double pointer to copy of environment variable
*/
char **copy_env(char **environ_copy, unsigned int environ_length)
{
char *variable;
unsigned int variable_length;
unsigned int i;
environ_copy = malloc(sizeof(char **) * (environ_length));
if (environ_copy == NULL)
{
errors(3);
return (NULL);
}
i = 0;
while (i < environ_length)
{
variable = environ[i];
variable_length = _strlen(variable);
environ_copy[i] = malloc(sizeof(char) * variable_length + 1);
if (environ_copy[i] == NULL)
{
errors(3);
return (NULL);
}
_strcpy(environ_copy[i], environ[i]);
i++;
}
return (environ_copy);
}