-
Notifications
You must be signed in to change notification settings - Fork 1
/
environment_handlers.c
92 lines (80 loc) · 1.85 KB
/
environment_handlers.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
#include "shell.h"
/**
* _getenv - get an environment variable
* @name: the name of the environment variable to look for
*
* Return: a pointer to the value in the environment,
* or NULL if there is no match
*/
char *_getenv(const char *name)
{
int i;
size_t len = _strlen(name);
for (i = 0; environ[i] != NULL; i++)
{
/* check if we found a match */
if (_strstr(environ[i], name) && environ[i][len] == '=')
{
/* move past the equal to sign and return the actual value */
return ((_strchr(environ[i], '=')) + 1);
}
}
return (NULL);
}
/**
* build_path - builds a list of paths in the PATH environment variable
* @head: a pointer to the head node
*
* Return: a pointer to the head onn success, else NULL on failure.
*/
path_t *build_path(path_t **head)
{
size_t i = 0;
char *path_value = NULL, **pathnames = NULL;
path_t *new_node = NULL, *tail = NULL;
path_value = _getenv("PATH");
if (path_value == NULL || *path_value == '\0')
return (NULL); /* PATH is not set */
pathnames = _strtok(path_value, ":");
if (pathnames == NULL)
return (NULL); /* couldn't get the list of PATH directories */
while (pathnames[i] != NULL)
{
new_node = malloc(sizeof(path_t));
if (new_node == NULL)
return (NULL);
new_node->pathname = _strdup(pathnames[i]);
_strcpy(new_node->pathname, pathnames[i]);
new_node->next = NULL;
if (*head == NULL)
{
(*head) = new_node;
}
else
{
tail = *head;
while (tail->next != NULL)
tail = tail->next;
tail->next = new_node;
}
/* free memory for the written value */
safe_free(pathnames[i]);
i++;
}
free_str(&pathnames);
return (*head);
}
/**
* print_path - prints the contents in the PATH variable
* @list: list of pathnames
*/
void print_path(path_t *list)
{
if (list == NULL)
return;
while (list != NULL)
{
printf("%s\n", list->pathname);
list = list->next;
}
}