-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsetenv.c
More file actions
76 lines (67 loc) · 1.62 KB
/
setenv.c
File metadata and controls
76 lines (67 loc) · 1.62 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
/*
** EPITECH PROJECT, 2025
** B-PSU-200-LYN-2-1-minishell1-pierre.baud
** File description:
** setenv
*/
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include "my.h"
int is_valid_name(char *name)
{
int i = 0;
if (name == NULL || name[0] == '\0') {
write(2, "setenv: Nom de variable invalide\n", 32);
return 0;
}
for (; name[i] != '\0'; i++) {
if (name[i] == '=') {
write(2, "setenv: Le nom ne peut pas contenir '='\n", 39);
return 0;
}
}
return 1;
}
int find_index_var(char *name, char **envc)
{
int name_len = my_strlen(name);
int i = 0;
for (; envc[i] != NULL; i++) {
if (my_strncmp(envc[i], name, name_len) == 0 &&
envc[i][name_len] == '=') {
return i;
}
}
return -1;
}
void update_var(int index, char *name, char *value, char **envc)
{
int name_len = my_strlen(name);
int value_len = my_strlen(value);
int total_len = name_len + value_len + 2;
char *new_entry = malloc(total_len * sizeof(char));
if (new_entry == NULL) {
write(2, "Erreur d'allocation mémoire\n", 29);
exit(84);
}
my_strcpy(new_entry, name);
my_strcat(new_entry, "=");
my_strcat(new_entry, value);
envc[index] = new_entry;
}
int my_setenv(char *name, char *value, char ***envc)
{
int index;
if (!is_valid_name(name))
return 1;
if (value == NULL)
value = "";
index = find_index_var(name, *envc);
if (index != -1) {
update_var(index, name, value, *envc);
} else {
add_new_var(name, value, envc);
}
return 0;
}