42_minishell/env/env1.c

118 lines
2.8 KiB
C
Raw Normal View History

2023-02-16 09:13:55 -05:00
/* ************************************************************************** */
/* */
/* ::: :::::::: */
2023-03-30 07:12:18 -04:00
/* env1.c :+: :+: :+: */
2023-02-16 09:13:55 -05:00
/* +:+ +:+ +:+ */
/* By: erey-bet <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2023/02/02 14:39:56 by erey-bet #+# #+# */
2023-04-18 07:30:17 -04:00
/* Updated: 2023/04/18 12:47:08 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)
2023-04-18 07:30:17 -04:00
{
2023-02-16 09:13:55 -05:00
current->next = ft_calloc(1, sizeof(t_list));
2023-04-18 07:30:17 -04:00
if (!current->next)
return ;
}
2023-02-16 09:13:55 -05:00
}
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;
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)
2023-04-18 07:30:17 -04:00
{
free(head);
2023-02-16 09:13:55 -05:00
return (NULL);
2023-04-18 07:30:17 -04:00
}
2023-02-16 09:13:55 -05:00
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]);
add_sort(head, var);
}
return (head);
}