-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathget_path.c
42 lines (40 loc) · 834 Bytes
/
get_path.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
#include "main.h"
/**
* get_path - gets the full path of a file
* @arg: file to find
* Return: pointer to full path
*/
char *get_path(char *arg)
{
char *path = get_env("PATH");
char *path_token, *fullpath, *fullpathtemp, *pathcopy = str_dup(path);
struct stat filestat;
if (!arg)
{
free(pathcopy);
return (NULL);
}
if (stat(arg, &filestat) == 0 && (arg[0] == '.' || arg[0] == '/'))
{
fullpath = strdup(arg);
free(pathcopy);
return (fullpath);
}
path_token = strtok(pathcopy, ":");
while (path_token)
{
fullpathtemp = concat(path_token, "/");
fullpath = concat(fullpathtemp, arg);
if (stat(fullpath, &filestat) == 0)
{
free(pathcopy);
free(fullpathtemp);
return (fullpath);
}
free(fullpathtemp);
free(fullpath);
path_token = strtok(NULL, ":");
}
free(pathcopy);
return (NULL);
}