-
Notifications
You must be signed in to change notification settings - Fork 0
/
get_path.c
53 lines (49 loc) · 1020 Bytes
/
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
#include "main.h"
/**
* get_path - find the full path of a command using
* the PATH environment variable
* @envp: env from main args
* @command: command to be run
* Return: full path
*/
char *get_path(char **envp, char *command)
{
char *new_command = NULL, *token;
char *path = _getenv(envp, "PATH");
DIR *dir;
struct dirent *entity;
if (!path)
return (NULL);
token = strtok(path, ":");
while (token)
{
dir = opendir(token);
if (!dir)
continue;
entity = readdir(dir);
while (entity)
{
if ((strcmp(entity->d_name, command)) == 0)
{
new_command = (char *) malloc(_strlen(token) + _strlen(command) + 2);
if (new_command == NULL)
{
free(path);
return (NULL);
}
_strcpy(new_command, token);
_strcat(new_command, "/");
_strcat(new_command, command);
closedir(dir);
free(path);
return (new_command);
}
entity = readdir(dir);
}
token = strtok(NULL, ":");
closedir(dir);
}
free(path);
free(new_command);
return (command);
}