-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathenv-list.c
147 lines (131 loc) · 2.26 KB
/
env-list.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
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
#include "shell.h"
/**
* list_path - create a list whith the direcories in the PATH.
* @env: environment variable.
* Return: a pointer to the new list.
*/
list_t *list_path(char **env)
{
list_t *head = NULL;
char **environ;
int len, i;
len = 0;
while (env[len])
len++;
environ = malloc(sizeof(char *) * len);
if (!environ)
{
perror("MALLOC");
return (NULL);
}
i = 0;
while (env[i])
{
environ[i] = str_dup(env[i]);
i++;
}
head = create_list(environ);
i = 0;
while (i < len)
{
free(environ[i]);
i++;
}
free(environ);
return (head);
}
/**
* create_list - create a list whith the direcories in the PATH.
* @environ: environment variable.
* Return: a pointer to the new list.
*/
list_t *create_list(char **environ)
{
list_t *head = NULL, *temp = NULL;
char *dir, *aux, *var_name, *var_value = NULL;
int i;
i = 0;
while (environ[i])
{
var_name = strtok(environ[i], "=");
if (str_twins(var_name, "PATH") == 0)
{
var_value = strtok(NULL, "\n");
break;
}
i++;
}
if (var_value)
{
i = 0;
aux = strtok(var_value, ":");
if (aux)
{
dir = str_dup(aux);
head = add_list(&head, dir);
aux = strtok(NULL, ":");
}
temp = head;
while (aux)
{
i++;
dir = str_dup(aux);
add_list(&head, dir);
temp = temp->next;
aux = strtok(NULL, ":");
}
}
else
perror("ERROR: var_value NULL\n");
return (head);
}
/**
* add_list - add a new node to the list.
* @head: pointer to the list.
* @dir: string to be placed in the new node.
* Return: pointer to the list.
*/
list_t *add_list(list_t **head, char *dir)
{
list_t *new, *aux = *head;
new = malloc(sizeof(list_t));
if (new == NULL)
{
perror("ERROR: unable to allocate memory\n");
return (NULL);
}
new->dir = dir;
new->next = NULL;
if (aux)
{
while (aux->next)
aux = aux->next;
aux->next = new;
}
else
*head = new;
return (new);
}
/**
* free_list - free the list of direcories.
* @head: pinter to the list.
*/
void free_list(list_t *head)
{
list_t *actual_node;
list_t *next_node;
if (head)
{
actual_node = head;
next_node = head->next;
while (next_node)
{
free(actual_node->dir);
free(actual_node);
actual_node = next_node;
next_node = next_node->next;
}
free(actual_node->dir);
free(actual_node);
}
}