-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlinked_env.c
125 lines (110 loc) · 2.28 KB
/
linked_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
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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
#include "shell.h"
/**
* create_envlist - creates a linked list with all environment
* variables in the extern environ variable
* Return: head of created list
*/
env_t *create_envlist(void)
{
env_t *head;
int i;
head = NULL;
for (i = 0; environ[i] != NULL; i++)
add_env(&head, environ[i]);
return (head);
}
/**
* add_env - adds another environmental variable to the end
* of the environemental variable linked list
* @head: head of the linked list
* @str: environmental variable value to store
* Return: the address of the new element, on fail, program exits
*/
env_t *add_env(env_t **head, char *str)
{
env_t *new_node;
env_t *temp;
new_node = safe_malloc(sizeof(env_t));
new_node->value = _strdup(str);
new_node->next = NULL;
if (*head == NULL)
*head = new_node;
else
{
temp = *head;
while (temp->next != NULL)
temp = temp->next;
temp->next = new_node;
}
return (new_node);
}
/**
* remove_env - removes an environmental variable
* @head: pointer to the head of the linked list
* @index: the nth node to delete
*/
void remove_env(env_t **head, int index)
{
env_t *temp;
env_t *dnode;
int i;
/*DEBUG: Shouldn't this just remove env by name, why by index?*/
i = 0;
temp = *head;
if (index == 0)
{
*head = (*head)->next;
_free(temp->value);
_free(temp);
}
else
{
while (i < index - 1)
{
temp = temp->next;
i++;
}
dnode = temp->next;
temp->next = dnode->next;
_free(dnode);
}
}
/**
* print_env - prints all environmental variables and its values
* @head: head pointer to the linked list
*/
void print_env(env_t *head)
{
env_t *temp;
temp = head;
while (temp != NULL)
{
_write(temp->value);
_write("\n");
temp = temp->next;
}
}
/**
* update_env - updates an environemental variable
* @envp: linked list of environemental variables
* @name: the name of variable to update;
* @value: the value to update env with
* @buf_size: buffer size
*/
void update_env(env_t *envp, char *name, char *value, int buf_size)
{
char *rep;
env_t *temp;
rep = safe_malloc(sizeof(char) * buf_size);
_memset(rep, '\0', buf_size);
_strcat(rep, name);
_strcat(rep, value);
for (temp = envp; temp != NULL; temp = temp->next)
{
if (_strstr(temp->value, name) != NULL && temp->value[0] == name[0])
{
temp->value = rep;
break;
}
}
}