-
Notifications
You must be signed in to change notification settings - Fork 0
/
get_env.c
60 lines (52 loc) · 1.4 KB
/
get_env.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
#include "shell.h"
/**
* c_strdup - custom string duplication; excludes beginning bytes
* @str: string to duplicate (e.g. environmental variable PATH=/bin:/bin/ls)
* @cs: number of bytes to exclude (e.g. excludes "PATH=")
* Return: string (e.g. /bin:/bin/ls)
*/
char *c_strdup(char *str, int cs)
{
char *duplicate_str;
int i, len = 0;
if (str == NULL) /* validate str input */
return (NULL);
/* calculate len + null terminator to malloc */
while (*(str + len))
len++;
len++;
/* allocate memory but exclude environmental variable title (PATH) */
duplicate_str = malloc(sizeof(char) * (len - cs));
if (duplicate_str == NULL)
return (NULL);
i = 0;
while (i < (len - cs))
{
*(duplicate_str + i) = *(str + cs + i);
i++;
}
return (duplicate_str);
}
/**
* get_env - finds and returns a copy of the requested environmental variable
* @str: string to store it in
* @env: entire set of environmental variables
* Return: copy of requested environmental variable
*/
char *get_env(char *str, list_t *env)
{
int j = 0, cs = 0;
while (env != NULL)
{
j = 0;
while ((env->var)[j] == str[j]) /* find desired env variable */
j++;
if (str[j] == '\0' && (env->var)[j] == '=')
break;
env = env->next;
}
while (str[cs] != '\0') /* find how many bytes in env variable title */
cs++;
cs++; /*counts 1 more for = sign*/
return (c_strdup(env->var, cs)); /* make a copy of variable w/o title */
}