-
Notifications
You must be signed in to change notification settings - Fork 0
/
locate.c
140 lines (123 loc) · 2.58 KB
/
locate.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
#include "shell.h"
char *fill_path_dir(char *path);
list_t *get_path_dir(char *path);
/**
* get_location - Locates a command in the PATH.
* @command: The command to locate.
*
* Return: If an error occurs or the command cannot be located - NULL.
* Otherwise - the full pathname of the command.
*/
char *get_location(char *command)
{
char **path, *temp;
list_t *dirs, *head;
struct stat st;
path = _getenv("PATH");
if (!path || !(*path))
return (NULL);
dirs = get_path_dir(*path + 5);
head = dirs;
while (dirs)
{
temp = malloc(_strlen(dirs->dir) + _strlen(command) + 2);
if (!temp)
return (NULL);
_strcpy(temp, dirs->dir);
_strcat(temp, "/");
_strcat(temp, command);
if (stat(temp, &st) == 0)
{
free_list(head);
return (temp);
}
dirs = dirs->next;
free(temp);
}
free_list(head);
return (NULL);
}
/**
* fill_path_dir - Copies path but also replaces leading/sandwiched/trailing
* colons (:) with current working directory.
* @path: The colon-separated list of directories.
*
* Return: A copy of path with any leading/sandwiched/trailing colons replaced
* with the current working directory.
*/
char *fill_path_dir(char *path)
{
int i, length = 0;
char *path_copy, *pwd;
pwd = *(_getenv("PWD")) + 4;
for (i = 0; path[i]; i++)
{
if (path[i] == ':')
{
if (path[i + 1] == ':' || i == 0 || path[i + 1] == '\0')
length += _strlen(pwd) + 1;
else
length++;
}
else
length++;
}
path_copy = malloc(sizeof(char) * (length + 1));
if (!path_copy)
return (NULL);
path_copy[0] = '\0';
for (i = 0; path[i]; i++)
{
if (path[i] == ':')
{
if (i == 0)
{
_strcat(path_copy, pwd);
_strcat(path_copy, ":");
}
else if (path[i + 1] == ':' || path[i + 1] == '\0')
{
_strcat(path_copy, ":");
_strcat(path_copy, pwd);
}
else
_strcat(path_copy, ":");
}
else
{
_strncat(path_copy, &path[i], 1);
}
}
return (path_copy);
}
/**
* get_path_dir - Tokenizes a colon-separated list of
* directories into a list_s linked list.
* @path: The colon-separated list of directories.
*
* Return: A pointer to the initialized linked list.
*/
list_t *get_path_dir(char *path)
{
int index;
char **dirs, *path_copy;
list_t *head = NULL;
path_copy = fill_path_dir(path);
if (!path_copy)
return (NULL);
dirs = _strtok(path_copy, ":");
free(path_copy);
if (!dirs)
return (NULL);
for (index = 0; dirs[index]; index++)
{
if (add_node_end(&head, dirs[index]) == NULL)
{
free_list(head);
free(dirs);
return (NULL);
}
}
free(dirs);
return (head);
}