-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathpath_functions.c
139 lines (125 loc) · 2.44 KB
/
path_functions.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
#include "shell.h"
/**
* _strstr - locate a substring
* @haystack: string to be looked through
* @needle: substring to be searched for in haystack
*
* Return: first occurence of the substring needle in haystack,
* or NULL is substring is not found
*/
char *_strstr(char *haystack, char *needle)
{
int i, j, needle_len, match_len;
char *substring = NULL;
needle_len = 0;
for (i = 0; needle[i] != '\0'; i++)
;
needle_len = i;
if (needle_len == 0)
return (haystack);
match_len = 0;
for (i = 0; haystack[i] != '\0'; i++)
{
for (j = 0; needle[j] != '\0'; j++)
{
if (haystack[i] != needle[j])
{
if (match_len > 0 && substring)
{
substring = NULL;
match_len = 0;
}
else
continue;
}
if (haystack[i] == needle[j])
{
if (substring == NULL)
substring = &haystack[i];
i++;
match_len++;
}
}
if (match_len == needle_len)
return (substring);
}
return (substring);
}
/**
* _getenv - get an environment variable
* @name: name of environment variable to look for
*
* Return: pointer to the value in the environment
* or NULL if there is no match
*/
char *_getenv(const char *name)
{
int i;
char *token = NULL;
for (i = 0; environ[i]; i++)
{
if (_strstr(environ[i], (char *)name))
{
token = strtok(environ[i], "=");
token = strtok(NULL, "=");
}
}
return (token);
}
/**
* add_node_end - adds a new node at the end of a `list_t` linked list
* @head: pointer to first node in linked list
* @str: string to be assigned to new node
*
* Return: address of the new element, or NULL if it failed
*/
list_t *add_node_end(list_t **head, char *str)
{
list_t *new, *i;
new = malloc(sizeof(list_t));
if (new == NULL)
return (NULL);
new->str = _strdup(str);
new->next = NULL;
if (*head == NULL)
{
*head = new;
}
else
{
for (i = *head; i->next != NULL; i = i->next)
;
i->next = new;
}
return (new);
}
/**
* build_linked_list - builds a linked list
* @path: pointer to value of environment variable PATH
* @head: pointer to pointer to head of a linked list
*/
void build_linked_list(char *path, list_t **head)
{
char *token;
token = strtok(path, ":");
while (token)
{
add_node_end(head, token);
token = strtok(NULL, ":");
}
}
/**
* free_list - frees a `list_t` linked list
* @head: pointer to first node
*/
void free_list(list_t *head)
{
list_t *tmp;
while (head != NULL)
{
tmp = head;
free(tmp->str);
head = head->next;
free(tmp);
}
}