-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathshell_locations.c
47 lines (44 loc) · 917 Bytes
/
shell_locations.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
#include "shell.h"
/**
* get_location - gives executable path of file
* @org_path: original path
* @new_file: executable file
* Return: absolute path to the executable file
*/
char *get_location(char *org_path, char *new_file)
{
char *dup_path = strdup(org_path);
char *parsed = strtok(dup_path, ":");
struct stat file_path;
char *path_memo = NULL;
do {
if (path_memo != NULL)
{
free(path_memo);
path_memo = NULL;
}
path_memo = malloc(strlen(parsed) + strlen(new_file) + 2);
if (path_memo == NULL)
{
perror("Error: malloc failed");
exit(EXIT_FAILURE);
}
strcpy(path_memo, parsed);
strcat(path_memo, "/");
strcat(path_memo, new_file);
strcat(path_memo, "\0");
if (stat(path_memo, &file_path) == 0 && access(path_memo, X_OK) == 0)
{
free(dup_path);
return (path_memo);
}
parsed = strtok(NULL, ":");
} while (parsed != NULL);
free(dup_path);
if (path_memo != NULL)
{
free(path_memo);
}
free(parsed);
return (NULL);
}