-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfile_loc.c
72 lines (63 loc) · 1.44 KB
/
file_loc.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
#include "main.h"
//char *full_path;
int startsWithForwardSlash(const char *str)
{
if(str!=NULL || str[0] == '/')
return (1);
return (0);
}
char *get_file_loc(char *path, char *file_name)
{
char *path_copy, *token;
struct stat file_path;
char *path_buffer = NULL;
path_copy = strdup(path);
token = strtok(path_copy, ":");
while(token)
{
if(path_buffer)
{
free(path_buffer);
path_buffer = NULL;
}
path_buffer = malloc(strlen(token) + strlen(file_name) + 2);
if(!path_buffer)
{
perror("Error: Memory Allocation Failed: ");
exit(EXIT_FAILURE);
}
strcpy(path_buffer, token);
strcat(path_buffer, "/");
strcat(path_buffer, file_name);
strcat(path_buffer, "\0");
if(stat(path_buffer, &file_path) ==0 && access(path_buffer, X_OK)==0)
{
free(path_copy);
return (path_buffer);
}
token = strtok(NULL, ":");
}
free(path_copy);
if(path_buffer)
free(path_buffer);
return (NULL);
}
char *get_file_path(char *file_name)
{
char *path = getenv("PATH");
char *full_path;
if(startsWithForwardSlash(file_name) && access(file_name, X_OK) ==0)
return (strdup(file_name));
if(!path)
{
perror("Path not found");
return (NULL);
}
full_path = get_file_loc(path, file_name);
if(full_path == NULL){
write(2, file_name, strlen(file_name));
write(2, ": command not found \n", 21);
return (NULL);
}
return (full_path);
}