-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathadd_path.c
More file actions
85 lines (75 loc) · 1.69 KB
/
add_path.c
File metadata and controls
85 lines (75 loc) · 1.69 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
#include "shell.h"
#include "path_list.h"
/**
* add_path - replace ordinary command with the actual command in PATH
* @args: an array of arguments (strings)
* @changed: assigns true / false to this value if it modifies argument
*
* Return: the restructured arguments, else NULL on error
*/
char **add_path(char **args, bool *changed)
{
struct stat file_stats;
char *cmd = NULL;
const char *FILE_SEP = "/";
dir_list_t *path = NULL, *tmp = NULL;
if (args == NULL || args[0] == NULL)
{
return (NULL);
}
if (stat(args[0], &file_stats) == 0)
{
(*changed) = false;
return (args);
}
path = path_list();
for (tmp = path; tmp != NULL; tmp = tmp->next)
{/* check path/cmd_name */
cmd = strjoin(tmp->dir, FILE_SEP, args[0]);
if (cmd == NULL)
break;
/* check if cmd is a file */
if (stat(cmd, &file_stats) == 0)
break;
free(cmd);
cmd = NULL;
}
free_dir_list(&path);
if (cmd == NULL)
{
return (NULL);
}
args[0] = cmd;
(*changed) = true;
return (args);
}
/**
* strjoin - joins two strings with a separator in between
* @str1: first string
* @sep: separator
* @str2: second string
*
* Description: if the return value is not NULL, ensure to free it
* Return: the concatenated string, else NULL
*/
char *strjoin(const char *str1, const char *sep, const char *str2)
{
char *joined = NULL;
int length = 0;
if (str1 == NULL || sep == NULL || str2 == NULL)
{
return (NULL);
}
length = strlen(str1) + strlen(sep) + strlen(str2) + 1;
joined = malloc(length * sizeof(char));
if (joined != NULL)
{
if (!(strcpy(joined, str1)))
return (NULL);
if (!(strcat(joined, sep)))
return (NULL);
if (!(strcat(joined, str2)))
return (NULL);
}
return (joined);
}