forked from jswini/simple_shell
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathget_path.c
100 lines (94 loc) · 1.6 KB
/
get_path.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
#include "shell_header.h"
/**
* add_node_end - adds a node to the end of a singly linked list
* @head: pointer to the list
* @str: string to store in the new node
*
* Return: pointer to new node
*/
paths *add_node_end(paths **head, const char *str)
{
paths *new, *last;
new = malloc(sizeof(paths));
if (!new)
return (NULL);
if (!str)
{
new->file_path = NULL;
}
else
{
new->file_path = _strdup(str);
if (!new->file_path)
{
free(new);
return (NULL);
}
}
new->next = NULL;
if (!*head)
{
*head = new;
}
else
{
last = (paths *)*head;
while (last->next)
{
last = last->next;
}
last->next = new;
}
return (new);
}
/**
* get_path - finds and tokenizes the path env and adds to linked list
*
* Return: the head of the path linked list
*/
paths *get_path(void)
{
int i;
char *path = NULL, *path_tok, *tempPath;
paths *path_list = NULL;
char delim[] = {':', '=', '\n'};
if (!environ)
return(NULL);
for (i = 0; environ[i] != NULL; i++)
{
if (_strncmp(environ[i], "PATH", 4) == 0)
{
path = _strdup(environ[i]);
break;
}
}
if (path == NULL)
{
return(NULL);
}
path_tok = strtok(path, delim);
path_tok = strtok(NULL, delim);
while (path_tok)
{
tempPath = _strcat(path_tok, "/");
add_node_end(&path_list, tempPath);
path_tok = strtok(NULL, delim);
free(tempPath);
}
free(path);
return (path_list);
}
/**
* free_list - frees memory allocated for a singly linked list
*
* @head: pointer to the list to free
*/
void free_list(paths *head)
{
paths *ptr = head;
if (!head)
return;
free_list(head->next);
free(ptr->file_path);
free(ptr);
}