-
Notifications
You must be signed in to change notification settings - Fork 0
/
handle_path.c
81 lines (71 loc) · 1.4 KB
/
handle_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
#include "shell.h"
/**
* getpath - get PATH enviroment varible as string
*
* @env: eviroment array.
*
* Return: PATH enviroment varible as string.
*/
char *getpath(char **env)
{
char *path = NULL;
int path_len = 0;
while (*env != NULL)
{
if (strncmp(*env, "PATH=", 5) == 0)
{
path_len = strlen(*env + 5);
path = malloc(sizeof(char) * (path_len + 1));
path[path_len] = '\0';
strcpy(path, *env + 5);
}
(void) *env++;
}
return (path);
}
/**
* _path - handle path of the command.
*
* @command_arr: array of args and command.
* @env: to get the path of the program.
*
* Return: Arr of exist commands.
*/
int _path(char **command_arr, char **env)
{
char *token;
char *full_path;
char *path;
char *path_copy;
if (strncmp(command_arr[0], "./", 2) == 0)
return (0);
path = getpath(env);
if (path == NULL)
return (0);
path_copy = malloc(strlen(path) + 1);
if (path_copy == NULL)
{
return (0);
}
strcpy(path_copy, path);
token = strtok(path_copy, ":");
while (token != NULL)
{
full_path = concat_command(command_arr[0], token);
if (access(full_path, X_OK) == 0)
{
free(command_arr[0]);
command_arr[0] = malloc(sizeof(char) * (strlen(full_path) + 1));
strcpy(command_arr[0], full_path);
free(full_path);
free(path);
free(path_copy);
return (1);
}
free(full_path);
token = strtok(NULL, ":");
}
free(path);
free(path_copy);
return (0);
}