-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path0_
133 lines (120 loc) · 2.81 KB
/
0_
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
#include "main.h"
/**
* put_paths - functions to set the array of the path
* @path: the specific array being set
* @num: tokens number
* @tok: tokened string
*/
void put_paths(char **path, const int num, char *tok)
{
int j;
for (j = 0; j < num; j++)
{
path[j] = our_strdup(tok);
tok += our_strlen(tok) + 1;
}
path[j] = NULL;
}
/**
* path_free - frees paths array to prevent memory leaks
* @path: the specific array being set
* @num: the tokens number
* @return_value: this is the value being returned
* Return: return value
*/
int path_free(char **path, int num, int return_value)
{
int j;
for (j = 0; j <= num; j++)
free(path[j]);
free(path);
return (return_value);
}
/**
* tokenize - this is the entry point
* Description: used to tokenize a string
* @s: the string beinng tokenized
* @c: the separator
* Return: num of tokens
*/
int tokenize(char *s, char c)
{
int j, num = 1;
for (j = 0; s[j]; j++)
{
if (s[j] == c)
{
num++;
s[j] = '\0';
}
}
return (num);
}
/**
* path - functions to sort out the path
* @av: the path
* Return: 0 on failure.
*/
int path(char **av)
{
struct stat st;
const char *p = our_getenv("PATH");
char filepath[256];
char **path = malloc(20 * sizeof(char *)), *tok;
int j, num = 1;
if (stat((*av), &st) == 0)
return (path_free(path, -1, 1));
if (p == NULL)
return (path_free(path, -1, 0));
tok = our_strdup(p);
num = tokenize(tok, ':');
put_paths(path, num, tok);
free(tok);
for (j = 0; j < num; j++)
{
our_strcpy(filepath, path[j]);
if (our_strncmp(filepath, (*av), our_strlen(filepath)) == 0)
{
if (stat((*av), &st) == 0)
return (path_free(path, num, 1));
}
else
{
our_strcat(filepath, "/");
our_strcat(filepath, (*av));
if (access(filepath, F_OK) == 0)
{
(*av) = our_strdup(filepath);
return (path_free(path, num, 2));
}
}
}
return (path_free(path, num, 0));
}
/**
* handle_path - Handles the PATH and executes the command if found.
* @command: The command to be executed.
* @args: The arguments for the command.
* Return: 0 on success, -1 on failure
* (command not found or permission denied).
*/
int handle_path(char *command, char **args)
{
int path_result = path(&command);
if (path_result == 0)
{
handle_error("command not found", command);
return (-1);
}
else if (path_result == -1)
{
handle_error("permission denied", command);
return (-1);
}
else if (path_result == 2)
{
execute_command(command, args);
return (0);
}
return (-1);
}