-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathisPath.c
101 lines (84 loc) · 1.97 KB
/
isPath.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
#include "shell.h"
/**
* isPath - searches directories in the PATH for the command
* @cmd: address of file to be searched for
*
* Description: isPath() will search directories in the path environment
* variable for the given file. If the the file is found it will modify the
* given string to reflect the absolute pathname of the given file, else the
* string is not changed.
*
* Return: 1 if file was found, 0 if not found, -1 on any failure
*/
int isPath(char **cmd)
{
char *environ = NULL, *directory = NULL;
int err = 0;
if (!is_abs_path(*cmd))
return (searchDIR(cmd, NULL));
environ = _strdup(_getenv("PATH"));
if (!environ)
return (0);
directory = _strtok(environ, ":");
while (directory)
{
err = searchDIR(&directory, *cmd);
if (err == -1)
{
free(environ);
return (-1);
}
if (err == 1)
break;
directory = _strtok(NULL, ":");
}
if (directory)
*cmd = make_path(directory, *cmd);
else
return (0);
free(environ);
if (errno || !(*cmd))
return (-1);
return (1);
}
/**
* is_abs_path - check if first character/s of cmd are "/" or "./" or "../"
* @cmd: the string to be checked
*
* Return: 0 if is absolute pathname, a +/- int if not
*/
int is_abs_path(char *cmd)
{
int diff = 0;
diff = _strncmp(cmd, "/", 1);
if (diff)
diff = _strncmp(cmd, "./", 2);
if (diff)
diff = _strncmp(cmd, "../", 3);
return (diff);
}
/**
* make_path - concatenates a directory string with a file string
* @directory: the directory pathname
* @file: the filename
*
* Return: pointer to the absolute pathname, NULL on failure
*/
char *make_path(char *directory, char *file)
{
char *path = NULL;
size_t p_len = _strlen(directory) + _strlen(file) + 2;
if (!directory || !file)
return (NULL);
path = malloc(sizeof(*path) * p_len);
_memset(path, '\0', p_len);
if (path)
{
_strncpy(path, directory, _strlen(directory));
_strncat(path, "/\0", 1);
_strncat(path, file, _strlen(file));
}
else
perror("make_path: Malloc fail");
return (path);
}