-
Notifications
You must be signed in to change notification settings - Fork 0
/
pathparser.c
135 lines (121 loc) · 2.4 KB
/
pathparser.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
#include "shellhead.h"
/**
* pathval - Appends executable to directories in path
* @execcpy: Copy of executable command
* @currentpath: The current node in the path linked list
* Return: Character pointer of executable appended to pathname
*/
char *pathval(char *execcpy, pathlist *currentpath)
{ /** helper for _execve in helpers.c */
char *pathval;
pathval = _strdup(currentpath->str); /** /dir1 */
pathval = _strcat(pathval, "/"); /** /dir1/ */
pathval = _strcat(pathval, execcpy); /** /dir1/command */
return (pathval);
}
/**
* pathparser - parses environ path
* @val: path string, untokenized
* @h: linked list to store path tokens
* Return: pointer to head of linked list
*/
pathlist *pathparser(char *val, pathlist *h)
{ /** separates path values by : delimiters in environ var $PATH */
char *valptr = NULL;
int i = 0, j = -1, k = 0;
if (val == NULL || val[0] == '\0')
{
add_node_end(&h, "");
return (h); }
if (val[0] == ':')
j = 0;
else if (val[_strlen(val) - 1] == ':')
j = _strlen(val) - 1;
else
{
while (val[i])
{
if (val[i] == ':')
{
k++;
if (val[i + 1] == ':')
{
j = k;
break; }
}
i++; }
}
i = -1;
valptr = _strtok(val, ":");
while (valptr)
{
i++;
if (i == j)
{
add_node_end(&h, "");
continue;
}
add_node_end(&h, valptr);
valptr = _strtok(NULL, ":");
}
free(val);
return (h);
}
/**
* add_node_end - adds new node in linked list
* @head: head of linked list - node 1
* @str: node data value
* Return: pointer to struct
*/
pathlist *add_node_end(pathlist **head, const char *str)
{
pathlist *new, *temp;
new = (pathlist *) malloc(sizeof(pathlist));
if (new == NULL)
return (NULL);
if (str == NULL)
return (NULL);
new->str = _strdup(str);
new->next = NULL;
if (*head == NULL)
{
*head = new;
return (*head);
}
else
{
temp = *head;
while (temp->next != NULL)
temp = temp->next;
temp->next = new;
}
return (temp);
}
/**
* print_pathlist - prints pathlist string from struct
* @h: head of linked list
*/
void print_pathlist(const pathlist *h)
{
while (h != NULL)
{
write(STDOUT_FILENO, h->str, _strlen(h->str));
write(STDOUT_FILENO, "\n", 1);
h = h->next;
}
}
/**
* free_list - frees memory of linked list
* @head: head node of linked list
*/
void free_list(pathlist *head)
{
pathlist *tmp = head;
while (head != NULL)
{
tmp = head;
free(tmp->str);
head = head->next;
free(tmp);
}
}