-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathfindPathFuncs.c
More file actions
109 lines (95 loc) · 2.05 KB
/
findPathFuncs.c
File metadata and controls
109 lines (95 loc) · 2.05 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
#include "holberton.h"
/**
* getKeyValue - gets pointer to the value string
*
* @key: key we want to find
* Return: pointer to key value after the =
*/
char *getKeyValue(char *key)
{
int i = 0;
char *tmp = NULL;
while (environ[i] && tmp == NULL)
{
tmp = _strstr(environ[i], key);
i++;
}
tmp = _strstr(tmp, "="), tmp++;
return (tmp);
}
/**
* getPathArgs - finds command path
*
* @prog: command we want to run
* Return: executable path of command
*/
char *getPathArgs(char *prog)
{
char *tmp;
char **tmp_args;
char *tmp_env;
tmp = getKeyValue("PATH");
tmp_env = _stralloc(1, tmp);
tmp_args = getToken(&tmp_env, ":");
tmp = get_x_args(tmp_args, prog);
free(tmp_env);
free(tmp_args);
return (tmp);
}
/**
* get_x_args - tests if path is executable
*
* @env_paths: path stings
* @program: command
* Return: string with full path
*/
char *get_x_args(char **env_paths, char *program)
{
int i = 1;
char *tmp;
tmp = _stralloc(3, env_paths[0], "/", program);
while (access(tmp, X_OK) == -1 && env_paths[i] != NULL)
{
free(tmp);
tmp = _stralloc(3, env_paths[i], "/", program);
i++;
}
if (env_paths[i] == NULL)
return (NULL);
else
return (tmp);
}
/**
* _stralloc - allocates and concats a string without realloc
* @count: number of arguements
* Return: the concat and allocated string
*/
char *_stralloc(int count, ...)
{
va_list list;
char *tmp_arg;
char *tmp_ptr;
char *tmp_return;
int sLen;
int aLen;
va_start(list, count);
tmp_arg = va_arg(list, char *), count--;
aLen = _strlen(tmp_arg);
tmp_return = malloc(sizeof(char) * aLen + 1);
if (tmp_return == NULL)
exit(EXIT_FAILURE);
_strcpy(tmp_return, tmp_arg);
while (count != 0)
{
tmp_arg = va_arg(list, char *), count--;
sLen = _strlen(tmp_return), aLen = _strlen(tmp_arg);
tmp_ptr = malloc(sizeof(char) * (sLen + aLen) + 1);
if (tmp_ptr == NULL)
perror("check if second malloc failed");
if (tmp_return != NULL)
_strcpy(tmp_ptr, tmp_return), free(tmp_return);
_strcat(tmp_ptr, tmp_arg), tmp_return = tmp_ptr;
}
va_end(list);
return (tmp_return);
}