42_minishell/env/env1.c

113 lines
2.8 KiB
C
Raw Normal View History

2023-02-16 09:13:55 -05:00
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* env.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: erey-bet <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2023/02/02 14:39:56 by erey-bet #+# #+# */
/* Updated: 2023/03/09 19:01:05 by erey-bet ### ########.fr */
2023-02-16 09:13:55 -05:00
/* */
/* ************************************************************************** */
#include "env_private.h"
2023-02-16 09:13:55 -05:00
void add_sort(t_list **head, t_env *var)
{
t_list *current;
t_env *last;
current = *head;
2023-02-17 11:46:12 -05:00
while (current->next != NULL
2023-02-23 07:36:26 -05:00
&& ft_strcmp(var->key, ((t_env *)(current->content))->key) > 0)
2023-02-16 09:13:55 -05:00
current = current->next;
if (current->content == NULL)
current->content = var;
else
{
last = NULL;
swap_env_3((void **)&last, &current->content, (void **)&var);
while (current->next != NULL)
{
current = current->next;
swap_env(&current->content, (void **)&last);
}
}
if (current->next == NULL)
current->next = ft_calloc(1, sizeof(t_list));
}
char *get_value_by_key(char *key, t_list **head)
{
t_list *current;
current = *head;
while (current->next != NULL)
{
if (ft_strcmp(((t_env *)current->content)->key, key) == 0)
return (((t_env *)current->content)->value);
current = current->next;
}
return (NULL);
2023-02-16 09:13:55 -05:00
}
int set_value_by_key(char *key, char *value, t_list **head)
{
t_list *current;
current = *head;
while (current->next != NULL)
{
if (ft_strcmp(((t_env *)current->content)->key, key) == 0)
{
free(((t_env *)current->content)->value);
((t_env *)current->content)->value = value;
return (0);
}
current = current->next;
}
return (1);
}
int create_value_by_key(char *key, char *value, t_list **head)
{
t_env *content;
2023-02-16 09:13:55 -05:00
if (set_value_by_key(key, value, head) == 0)
return (0);
content = ft_calloc(1, sizeof(t_env));
if (content == NULL)
return (1);
content->key = key;
content->value = value;
2023-03-09 09:07:36 -05:00
content->original = 0;
2023-02-16 09:13:55 -05:00
add_sort(head, content);
return (0);
}
t_list **init_env(char **env)
{
t_list **head;
int i;
t_env *var;
head = ft_calloc(1, sizeof(t_list *));
if (head == NULL)
return (NULL);
*head = ft_calloc(1, sizeof(t_list));
if (*head == NULL)
return (NULL);
i = -1;
while (env[++i])
{
var = ft_calloc(1, sizeof(t_env));
if (var == NULL)
return (NULL);
var->key = get_key(env[i]);
var->value = get_value(env[i]);
2023-03-09 09:07:36 -05:00
var->original = 1;
2023-02-16 09:13:55 -05:00
add_sort(head, var);
}
return (head);
}