-
Notifications
You must be signed in to change notification settings - Fork 0
/
get_path.c
46 lines (42 loc) · 882 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
#include "sh.h"
/**
* find_path - find the correct path of the command
*@command: command to recive.
*
* Return: the full path of the command or NULL in failure
*/
char *find_path(char *command)
{
char *path_copy, *token, *path_env, *full_path;
struct stat st;
path_env = getenv("PATH");
if (path_env == NULL)
{
perror("PATH");
return (NULL);
}
path_copy = strdup(path_env);
if (path_copy == NULL)
{
perror("ERROR");
return (NULL);
}
token = strtok(path_copy, ":");
while (token)
{
full_path = malloc(sizeof(char) * 1024);
sprintf(full_path, "%s/%s", token, command);
if (stat(full_path, &st) == 0)
{
command = NULL;
command = malloc(sizeof(char) * (strlen(full_path) + 1));
strcpy(command, full_path);
free(path_copy);
return (command);
}
token = strtok(NULL, ":");
free(full_path);
}
free(path_copy);
return (NULL);
}