-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpath.c
49 lines (47 loc) · 996 Bytes
/
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
#include "shell.h"
/**
* path_to_argv - find the path to a command
* @command: command-line argument
* Return: path, if found, or null, if !exist
*/
char *path_to_argv(char *command)
{
const char *path = getenv("PATH");
struct stat buffer;
char *path_copy, *path_token, *file_path;
int cmd_len, dir_len;
if (!path)
return (NULL);
path_copy = strdup(path);
if (!path_copy)
return (NULL);
cmd_len = str_len(command);
path_token = str_tok(path_copy, ":");
while (path_token != NULL)
{
dir_len = strlen(path_token);
file_path = malloc(dir_len + cmd_len + 2);
if (!file_path)
{
free(path_copy);
return (NULL);
}
str_cpy(file_path, path_token);
str_cat(file_path, "/");
str_cat(file_path, command);
if (stat(file_path, &buffer) == 0)
{
free(path_copy);
return (file_path);
}
else
{
free(file_path);
path_token = str_tok(NULL, ":");
}
}
free(path_copy);
if (stat(command, &buffer) == 0)
return (strdup(command));
return (NULL);
}