-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathget_command.c
More file actions
58 lines (49 loc) · 1.13 KB
/
get_command.c
File metadata and controls
58 lines (49 loc) · 1.13 KB
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
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <stdlib.h>
#include "main.h"
/**
* get_command - checks if a command exists
* @command: a malloc'd string pointer representing command
*
* Return: pointer to original command string if command
* exists without /bin/ prefix,
* a malloc'd string if prefix was needed otherwise NULL
*/
char *get_command(char *command)
{
struct stat st;
char *full_command = NULL;
path_t *current, *head = NULL;
char *command_copy = _strdup(command);
if (!command || !command_copy)
return (NULL);
/* Path exists */
if (lstat(command_copy, &st) == 0)
{
return (command_copy);
}
free(command_copy);
/* Generates a linked list of all paths in PATH env variable*/
if (generate_path_list(&head) == NULL)
return (NULL);
current = head;
while (current)
{
full_command = prefix(current->path, command);
if (!full_command)
return (NULL);
/* Path exists */
if (lstat(full_command, &st) == 0)
{
free_path_list(&head);
return (full_command);
}
free(full_command);
current = current->next;
}
free_path_list(&head);
return (NULL);
}