-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathselector.c
More file actions
107 lines (99 loc) · 2.2 KB
/
selector.c
File metadata and controls
107 lines (99 loc) · 2.2 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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
#include "holberton.h"
/**
* search_path - verify the command in the path, return the binary address
* @token: commands splited in array
* @h: head of the path linked list
* @env: enviroment
* Return: -1 if path not found
*/
int search_path(char **token, const list_t *h, char **env)
{
char *bin_com = NULL;
struct stat st;
while (h != NULL)
{
bin_com = malloc(_strlen(token[0]) + _strlen(h->str) + 2);
_strcpy(bin_com, h->str);
_strncat(bin_com, "/", 1);
_strncat(bin_com, token[0], _strlen(token[0]));
if (stat(bin_com, &st) == 0 && token[0][0] != '.')
{
execve(bin_com, token, env);
}
h = h->next;
free(bin_com);
bin_com = NULL;
}
return (-1);
}
/**
* _divisor - split the path and store it in linked list
* @_path: the path
* @head: head of the path linked list
* Return: 0 if success
*/
int _divisor(char *_path, list_t **head)
{
char *str;
char *tmppath = NULL;
tmppath = malloc(_strlen(_path) + 1);
if (tmppath == NULL)
return (-1);
_strcpy(tmppath, _path);
str = strtok(tmppath, ":");
while (str != NULL)
{
add_node(head, str);
str = strtok(NULL, ":");
}
free(tmppath);
return (0);
}
/**
* com_split - split the input commands and flags and
* store it in double pointer
* @commands: command input from getline
* Return: the double pointer with commands
*/
char **com_split(char *commands)
{
char **token = NULL, *temp, *temp2, *tok = NULL;
int len = 0, i = 0;
temp2 = malloc(sizeof(char) * _strlen(commands) + 1);
if (temp2 == NULL)
return (NULL);
_strcpy(temp2, commands);
tok = strtok(commands, " \t");
if (*tok == '\n' || *tok == '\t' || *tok == '\r' || *tok == '\a')
{
free(temp2);
return (NULL);
}
while (tok)
len++, tok = strtok(NULL, " \t");
token = malloc(sizeof(char *) * (len + 1));
if (token == NULL)
return (NULL);
temp = strtok(temp2, " \n\t\r\a");
i = 0;
while (temp != NULL)
{
token[i] = _strdup(temp);
if (token[i] == NULL)
{ /*FREE TOKEN*/
free_tok(token);
return (NULL);
}
_strcpy(token[i], temp);
temp = strtok(NULL, " \n\t\r\a");
i++;
}
token[i] = NULL;
if (!(_strcmp(token[0], ".")) && token[1] == NULL)
{ /*FREE TOKEN*/
free_tok(token), free(temp2);
return (NULL);
}
free(temp2);
return (token);
}