-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcheckInPath.c
110 lines (102 loc) · 1.9 KB
/
checkInPath.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 "shell.h"
/**
* absolutepath - check for absolute pathname
* @txt: user input
*
* Return: info about path
*/
PathInfo absolutepath(char *txt)
{
PathInfo info = {0, ""};
if (access(txt, F_OK) == 0)
{
info.exists = 1;
_strncpy(info.fullpath, txt, BUFSIZE);
}
return (info);
}
/**
* relativepath - check for reltive pathname
* @txt: the user command
*
* Return: info about path
*/
PathInfo relativepath(char *txt)
{
PathInfo info = {0, ""};
char *cwd = getcwd(NULL, 0);
char fullpath[BUFSIZE];
char *str = custom_concat(cwd, txt, '/');
if (cwd == NULL)
{
perror("Eroor: getcwd");
return (info);
}
_strncpy(fullpath, str, BUFSIZE);
free(cwd);
free(str);
if (access(fullpath, F_OK) == 0)
{
info.exists = 1;
_strncpy(info.fullpath, fullpath, BUFSIZE);
}
return (info);
}
/**
* searchInPath - Handle other case
* @target: user input
* @env_path: the path
*
* Return: info about path
*/
PathInfo searchInPath(char *target, char *env_path)
{
PathInfo result = {0, ""};
char *path_copy = _strdup(env_path);
char *dir = strtok(path_copy, ":");
char fullpath[BUFSIZE];
char *str;
if (env_path != NULL)
{
while (dir != NULL)
{
str = custom_concat(dir, target, '/');
_strncpy(fullpath, str, BUFSIZE);
free(str);
if (access(fullpath, F_OK) == 0)
{
result.exists = 1;
_strncpy(result.fullpath, fullpath, BUFSIZE);
break;
}
dir = strtok(NULL, ":");
}
free(path_copy);
}
return (result);
}
/**
* checkInPath - Check is user command is in the PATH
* @txt: the command
*
* Return: Info about path
*/
PathInfo checkInPath(char *txt)
{
PathInfo result = {0, ""};
char *env_path = _getenv("PATH");
if (txt == NULL || txt[0] == '\0')
return (result);
if (txt[0] == '/')
{
result = absolutepath(txt);
return (result);
}
else
{
result = relativepath(txt);
if (result.exists)
return (result);
}
return (searchInPath(txt, env_path));
}