-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsetenv2.c
More file actions
62 lines (54 loc) · 1.31 KB
/
setenv2.c
File metadata and controls
62 lines (54 loc) · 1.31 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
/*
** EPITECH PROJECT, 2025
** B-PSU-200-LYN-2-1-minishell1-pierre.baud
** File description:
** setenv2
*/
#include "my.h"
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
void print_error_and_exit(void)
{
write(2, "Erreur d'allocation mémoire\n", 29);
exit(84);
}
char **allocate_new_env(int env_size)
{
char **new_env = malloc((env_size + 2) * sizeof(char *));
if (new_env == NULL)
print_error_and_exit();
return new_env;
}
void add_new_var(char *name, char *value, char ***envc)
{
int env_size = 0;
char **new_env;
int i = 0;
if (value == NULL)
value = "";
while ((*envc)[env_size] != NULL)
env_size++;
new_env = allocate_new_env(env_size);
for (; i < env_size; i++)
new_env[i] = (*envc)[i];
new_env[env_size] = create_new_entry(name, value);
new_env[env_size + 1] = NULL;
free(*envc);
*envc = new_env;
}
char *create_new_entry(char *name, char *value)
{
int total_len = 0;
char *new_entry;
if (value == NULL)
value = "";
total_len = my_strlen(name) + my_strlen(value) + 2;
new_entry = malloc(total_len * sizeof(char));
if (new_entry == NULL)
print_error_and_exit();
my_strcpy(new_entry, name);
my_strcat(new_entry, "=");
my_strcat(new_entry, value);
return new_entry;
}