-
Notifications
You must be signed in to change notification settings - Fork 0
/
path.c
73 lines (71 loc) · 1.37 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
#include "shell.h"
/**
* check_path - this function check the path of a command
*
* @command: the command to be searched
* Return: the path of the command
*/
char *check_path(char *command)
{
struct stat buff;
char *comm_path;
if (!stat(command, &buff))
{
comm_path = malloc(_strlen(command) + 1);
if (!comm_path)
{
free(comm_path);
return (NULL);
}
_strcpy(comm_path, command);
return (comm_path);
}
return (NULL);
}
/**
* get_path - this function returns the path of a command
*
* @command: the command to be searched
* Return: the path of the command
*/
char *get_path(char *command)
{
char *path, *pathcpy, *tkn, *comm_path = check_path(command);
struct stat buff;
if (comm_path)
return (comm_path);
free(comm_path);
path = _getenv();
pathcpy = malloc(sizeof(char) * 1000);
if (!pathcpy)
{
free(path);
free(pathcpy);
return (NULL);
}
_strcpy(pathcpy, path);
tkn = strtok(pathcpy, ":");
while (tkn)
{
comm_path = malloc(_strlen(tkn) + _strlen(command) + 2);
if (!comm_path)
{
free(pathcpy), free(tkn), free(comm_path);
return (NULL);
}
_strcpy(comm_path, tkn);
_strcat(comm_path, "/");
_strcat(comm_path, command);
_strcat(comm_path, "\0");
if (!stat(comm_path, &buff))
{
free(pathcpy);
return (comm_path);
}
tkn = strtok(NULL, ":");
free(comm_path);
}
free(pathcpy);
free(tkn);
return (NULL);
}