-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathget_location.c
46 lines (44 loc) · 987 Bytes
/
get_location.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
#include "main.h"
/**
* get_location - gets file location
* @command: string with command
*
* Return: string
*/
char *get_location(char *command)
{
char *path = NULL, *path_copy = NULL, *path_token = NULL, *file_path = NULL;
int command_length, directory_length;
struct stat buffer;
path = getenv("PATH");
if (path)
{
path_copy = _strdup(path);
command_length = _strlen(command);
path_token = _strtok(path_copy, ":");
while (path_token != NULL)
{
directory_length = _strlen(path_token);
file_path = allocate(command_length + directory_length + 2);
_strcpy(file_path, path_token);
_strcat(file_path, "/");
_strcat(file_path, command);
_strcat(file_path, "\0");
if (stat(file_path, &buffer) == 0)
{
free(path_copy);
return (file_path);
}
else
{
free(file_path);
path_token = _strtok(NULL, ":");
}
}
free(path_copy);
if (stat(command, &buffer) == 0)
return (command);
return (NULL);
}
return (NULL);
}