-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathpath_functions.c
77 lines (73 loc) · 1.56 KB
/
path_functions.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
#include "main.h"
/**
* get_path - retrieve directories from the PATH environment
*
* Return: an array of strings containing the directories from the PATH
*/
char **get_path(void)
{
char *path = getenv("PATH"), *token, **path_directories = NULL;
char *buff = NULL;
int i = 0;
if (path == NULL)
{
print_error_exec();
exit_status = 127;
exit(exit_status);
}
path_directories = malloc(sizeof(char *) * 50);
if (path_directories == NULL)
{
perror("Memory allocation failed");
return (NULL);
}
while (environ[i] != NULL)
{
if (strstr(environ[i], "PATH") != NULL && environ[i][4] == '=')
{
path = environ[i];
break;
}
i++;
}
for (i = 0; i < 5; i++)
path++;
token = _strdup(path);
buff = strtok(token, ":");
for (i = 0; buff != NULL; i++)
{
path_directories[i] = _strdup(buff);
buff = strtok(NULL, ":");
}
if (path_directories[0] == NULL)
i++;
path_directories[i] = NULL;
free(token);
return (path_directories);
}
/**
*concat_path - concatenate the input with the PATH environment variables
*
*@exec_arg: the input to be concatenated
*
* Return: a pointer to the concatenated path, or otherwise NULL
*/
char *concat_path(char **exec_arg)
{
char **path = get_path();
char *file_path = NULL;
int i = 0, len = 0;
for (i = 0; path[i] != NULL; i++)
{
len = _strlen(exec_arg[0]) + _strlen(path[i]) + 2;
file_path = malloc(len);
_strcpy(file_path, path[i]);
_strcat(file_path, "/");
_strcat(file_path, exec_arg[0]);
if (access(file_path, F_OK) != -1)
break;
free(file_path);
}
free_contents(path);
return (file_path);
}