-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpath.c
More file actions
115 lines (100 loc) · 1.79 KB
/
path.c
File metadata and controls
115 lines (100 loc) · 1.79 KB
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
#include "shell.h"
/**
* free_mem - frees pathlist
* @pathlist: ...
*/
void free_mem(char **pathlist)
{
int i = 0;
while (pathlist[i])
{
free(pathlist[i]);
i++;
}
free(pathlist[i]);
free(pathlist);
}
/**
* getpath - store the path
* directories in arrays
* @path: path value
*
* Return: pointer to pointer
* of path directories
*/
char **getpath(char *path)
{
int i = 0, j = 0;
char *token, **pathlist, *delim = ":";
if (path == NULL)
return (NULL);
while (path[i])
{
if (path[i] == ':')
j++;
i++;
}
pathlist = malloc(sizeof(char *) * (j + 2));
if (pathlist == NULL)
{
free(path);
return (NULL);
}
i = 0;
j = 0;
token = strtok(path, delim);
while (token)
{
i = _strlen(token) + 2;
pathlist[j] = malloc(sizeof(char) * i);
_strcpy(pathlist[j], token);
_strcat(pathlist[j], "/");
token = strtok(NULL, delim);
j++;
}
pathlist[j] = NULL;
free(path);
return (pathlist);
}
/**
* check_path - path handler
* @shellf: shell info
*
* Return: 1 if found 0 if otherwise
*/
int check_path(shell_info shellf)
{
char *path, *temp_chain, *oldcomm;
char **pathlist;
int i = 0;
struct stat fstat;
if (shellf.args == NULL || shellf.args[0] == NULL)
return (-1);
if (stat(shellf.args[0], &fstat) == 0)
return (1);
path = _getenv("PATH");
if (path == NULL)
return (0);
pathlist = getpath(path);
if (pathlist == NULL)
return (0);
while (pathlist[i])
{
temp_chain = malloc(sizeof(char) *
(_strlen(pathlist[i]) + _strlen(shellf.args[0]) + 1));
_strcpy(temp_chain, pathlist[i]);
_strcat(temp_chain, shellf.args[0]);
if (stat(temp_chain, &fstat) == 0)
{
oldcomm = shellf.args[0];
shellf.args[0] = temp_chain;
free(oldcomm);
free_mem(pathlist);
return (1);
}
free(temp_chain);
i++;
}
free_mem(pathlist);
return (0);
}