-
Notifications
You must be signed in to change notification settings - Fork 1
/
file_path.c
37 lines (34 loc) · 829 Bytes
/
file_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
#include "shell.h"
/**
* get_file_path - get PATH
* @name: name of command
* Return: a full path of name or name it self on failure
*/
char *get_file_path(char *name)
{
char *PATH = _getenv("PATH"), *fpath = NULL;
char *tokenized = _strtok(PATH, ":", 0);
struct stat fileinfo;
if (!name)
return (NULL);
if (*name == '/' || *name == '.')
{
fpath = _malloc(_strlen(name) * sizeof(char) + 1);
_strcpy(fpath, name);
return (fpath);
}
while (tokenized)
{
fpath = _malloc((_strlen(tokenized) + _strlen(name) + 1) * sizeof(char) + 1);
_strcpy(fpath, tokenized);
_strcat(fpath, "/");
_strcat(fpath, name);
if (!stat(fpath, &fileinfo))
return (fpath);
free(fpath);
tokenized = _strtok(NULL, ":", 0);
}
fpath = _malloc(_strlen(name) * sizeof(char) + 1);
_strcpy(fpath, name);
return (fpath);
}