-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpath.c
110 lines (95 loc) · 2.19 KB
/
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
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
#include "main.h"
/**
* tokenize_path - the PATH environment variable into an array of strings.
* @rep: The PATH environment variable.
* Return: An array of strings containing the individual paths in
* the PATH environment variable, or NULL if an error occurred.
*/
char **tokenize_path(char *rep)
{
int i = 0;
char **tokenized = malloc(sizeof(char *) * 30);
char *token = strtok(rep, ":");
if (tokenized == NULL)
{
free(rep);
return (NULL);
}
while (token != NULL)
{
tokenized[i] = token;
token = strtok(NULL, ":");
i++;
}
tokenized[i] = NULL;
return (tokenized);
}
/**
* check_file_exists_and_is_executable - Check if the file exists
* and is executable.
* @file_path: The path to the file.
* Return: 1 if the file exists and is executable, 0 otherwise.
*/
int check_file_exists_and_is_executable(char *file_path)
{
return (access(file_path, X_OK) == 0);
}
/**
* construct_full_path - Construct a full path from a
* relative path and a command name.
* @relative_path: The relative path.
* @command: The command name.
* Return: A full path to the command, or NULL if an error occurred.
*/
char *construct_full_path(char *relative_path, char *command)
{
size_t length = strlen(relative_path) + strlen(command) + 2;
char *full_path = malloc(length);
if (full_path == NULL)
{
free(full_path);
return (NULL);
}
strcpy(full_path, relative_path);
strcat(full_path, "/");
strcat(full_path, command);
return (full_path);
}
/**
* path - Find the path to a command.
* @rep: The PATH environment variable.
* @command: The command name.
* Return: The path to the command, or NULL if the command does
* not exist or is not executable.
*/
char *path(char *rep, char *command)
{
char **tokenized = tokenize_path(rep);
int i = 0;
if (tokenized == NULL)
{
free(command);
return (NULL);
}
while (tokenized[i] != NULL)
{
char *full_path = construct_full_path(tokenized[i], command);
if (full_path == NULL)
{
free(tokenized);
return (NULL);
}
if (check_file_exists_and_is_executable(full_path))
{
free(tokenized);
free(rep);
return (full_path);
}
free(full_path);
full_path = NULL;
i++;
}
free(tokenized);
free(rep);
return (NULL);
}