-
Notifications
You must be signed in to change notification settings - Fork 0
/
path_handle.c
87 lines (75 loc) · 1.47 KB
/
path_handle.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
#include "main.h"
#include "strtow.h"
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
/**
* is_path - if path not absolute
* @path: path of function
*
* Return: 1 (not absolute) 0 (absolute)
**/
int is_path(char *path)
{
if (_strlen(path) >= 2)
{
if ((path[0] == '.' && path[1] == '/') || path[0] == '/' ||
(path[0] == '.' && path[1] == '.' && path[2] == '/'))
return (1);
}
return (0);
}
/**
* make_path - make path to file from directory and file
* @path: path to directory
* @file: file
* Return: New Path
**/
char *make_path(char *path, char *file)
{
char *npath;
if (path == NULL || file == NULL)
return (NULL);
npath = malloc(sizeof(char) *
(_strlen(path) + _strlen(file) + 2));
if (!npath)
return (NULL);
_strcpy(npath, path);
npath[_strlen(path)] = '/';
npath[_strlen(path) + 1] = '\0';
_strcat(npath, file);
return (npath);
}
/**
* path_match - find directory insid PATH
* that file resides in if any
* @exec: executable name
* Return: full path of executable or NULL if it's not found
**/
char *path_match(char **exec)
{
char **arr_p, *p, *path;
int i = 0;
struct stat st;
path = _getenv("PATH");
if (_strlen(path) == 0)
return (NULL);
arr_p = strtow(path, ':');
if (!arr_p)
return (NULL);
while (arr_p[i] != NULL)
{
p = make_path(arr_p[i], *exec);
if (stat(p, &st) == 0)
{
free(*exec);
*exec = p;
free_tow(arr_p);
return (p);
}
free(p);
i++;
}
free_tow(arr_p);
return (NULL);
}