-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgetenv
More file actions
48 lines (41 loc) · 722 Bytes
/
getenv
File metadata and controls
48 lines (41 loc) · 722 Bytes
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
#include "shell.h"
#include <stdlib.h>
/**
* getenv - retrieves the value of an environment variable
* @name: var
* Return: variable name (var)
*/
char *getenv(const char *name)
{
list_t *node = info->env;
char *a;
size_t length;
while (node)
{
a = starts_with(node->str, name);
if (a && *a)
{
/* Calculate the length of the string */
length = 0;
while (a[length] != '\0')
{
length++;
}
/* Allocate memory for the new string */
char *var = malloc((length + 1) * sizeof(char));
if (var == NULL)
{
return (NULL); /* Memory allocation failed */
}
/* Copy the string to the newly allocated memory */
for (size_t i = 0; i <= length; i++)
{
var[i] = a[i];
}
free(a);
return (var);
}
node = node->next;
}
return (NULL);
}