-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathenviroment.c
executable file
·88 lines (76 loc) · 1.79 KB
/
enviroment.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
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
#include "main.h"
/**
* cmp_env_name - compares env variables names to name passed.
* @nenv: name of the environment variable.
* @name: name passed.
* Return: 0 if no match, else index to ('=' + 1).
*/
int cmp_env_name(const char *nenv, const char *name)
{
int idx;
for (idx = 0; nenv[idx] != '='; idx++)
{
if (nenv[idx] != name[idx]) /* not a match */
{
return (0);
}
}
return (idx + 1); /* ('=' + 1) */
}
/**
* _getenv - Gets an environment variable.
* @name: name of the environment variable.
* Return: value of the environment variable if is found,
* else, returns NULL.
*/
char *_getenv(const char *name)
{
char *env_val;
int idx, mov;
env_val = NULL;
mov = 0; /* used to store int value of index of ('=' + 1) */
/* Compare all environment variables */
/* environ is declared in the "main.h" */
for (idx = 0; environ[idx]; idx++)
{
/* check for match and store index of ('=' + 1) */
mov = cmp_env_name(environ[idx], name);
if (mov)
{
/* store value from ('=' + 1) of environ[idx] */
env_val = environ[idx];
break;
}
}
if (mov == 0 || environ[idx] == NULL) /* check mov & match */
{
return (NULL);
}
return (env_val + mov);
}
/**
* _env - prints the evironment variables.
* @environ: environmental variables
* Return: 1 for success.
*/
int _env(char **environ)
{
int i;
ssize_t bytes_written;
for (i = 0; environ[i]; i++)
{
bytes_written = write(STDOUT_FILENO, environ[i], _strlen(environ[i]));
if (bytes_written == -1 || bytes_written != _strlen(environ[i]))
{
fprintf(stderr, "Failed to write environment variable\n");
return (-1);
}
bytes_written = write(STDOUT_FILENO, "\n", 1);
if (bytes_written == -1 || bytes_written != 1)
{
fprintf(stderr, "Failed to write newline\n");
return (-1);
}
}
return (1);
}