-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpath_related2.c
101 lines (88 loc) · 1.72 KB
/
path_related2.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
#include "shell.h"
/**
* countSlashes - Counts forward slashes in a string.
* @str: Input string.
*
* Useful for checking if a command was passed using its
* absolute path, e.g., "/bin/ls" instead of "ls."
*
* Return: Number of forward slashes.
*/
int countSlashes(char *str)
{
int i, len, slashes = 0;
len = _strlen(str);
for (i = 0; i < len; i++)
{
if (str[i] == '/')
slashes++;
}
return (slashes);
}
/**
* checkAbsPath - Checks if an absolute path passed exists.
* @str: Given command.
*
* Return: Absolute path if it exists, NULL otherwise.
*/
char *checkAbsPath(char *str)
{
char *cmd;
cmd = _strdup(str);
if (!cmd)
{
perror("checkAbsPath");
return (NULL);
}
if (access(cmd, X_OK) == 0)
return (cmd);
return (NULL);
}
/**
* extractCmd - Gets command from its absolute path.
* @str: Absolute path of command.
*
* Return: Command, or NULL on failure.
*/
char *extractCmd(char *str)
{
int i, j = 0, lastSlash = 0, len;
char *cmd;
len = _strlen(str);
for (i = 0; i < len; i++)
{
if (str[i] == '/')
lastSlash = i;
}
cmd = malloc(len - lastSlash);
if (!cmd)
{
perror("extractCmd");
return (NULL);
}
for (i = lastSlash; i < len; i++)
cmd[j++] = str[i];
cmd[j] = '\0';
return (cmd);
}
/**
* _realloc - Reallocates memory as necessary.
* @lineptr: Double pointer to line storage array.
* @n: Size of memory to allocate.
* @bytesRead: Total bytes read into lineptr.
*
* Return: lineptr with updated memory, or NULL on failure.
*/
char *_realloc(char **lineptr, int n, ssize_t bytesRead)
{
ssize_t i;
char *tmp;
tmp = (char *)malloc(n);
if (!tmp)
return (NULL);
for (i = 0; i < bytesRead; i++)
tmp[i] = (*lineptr)[i];
free(*lineptr);
*lineptr = tmp;
return (*lineptr);
}