-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgetenv.c
More file actions
103 lines (87 loc) · 1.52 KB
/
getenv.c
File metadata and controls
103 lines (87 loc) · 1.52 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
#include "shell.h"
/**
* _getenv - search for an environment varaibale
* @name: name of the variable
*
* Return: the value
*/
char *_getenv(char *name)
{
int i = 0, j = 0, k = 0;
char *value;
if (name == NULL)
return (NULL);
while (environ[i][j] != '=')
{
if (environ[i][j] != name[j])
{
j = 0;
i++;
if (environ[i] == NULL)
break;
continue;
}
j++;
}
if (environ[i] == NULL)
return (NULL);
while (environ[i][j] != '=')
j++;
value = malloc(sizeof(char) * (_strlen(environ[i]) - j));
if (value == NULL)
return (NULL);
j++;
while (environ[i][j])
{
value[k] = environ[i][j];
j++;
k++;
}
value[k] = '\0';
return (value);
}
/**
* _setenv - set an environment variable
* @name: name
* @value: value
*
* Return: 1 on success
*/
int _setenv(char *name, char *value)
{
char *temp = NULL, *val;
int i = 0, is_overwrite = 0;
val = _getenv(name);
if (val != NULL)
{
is_overwrite = 1;
temp = malloc(sizeof(char) * (_strlen(val) + _strlen(name) + 2));
if (temp == NULL)
return (-1);
_strcpy(temp, name);
_strcat(temp, "=");
_strcat(temp, val);
while (environ[i])
{
if (_strcmp(temp, environ[i]) == 0)
break;
i++;
}
} else
{
while (environ[i])
i++;
}
environ[i] = malloc(sizeof(char) * (_strlen(name) + _strlen(value) + 2));
if (environ[i] == NULL)
return (-1);
_strcpy(environ[i], name);
_strcat(environ[i], "=");
_strcat(environ[i], value);
if (!is_overwrite)
environ[i + 1] = NULL;
free(val);
if (temp)
free(temp);
return (1);
}