MiniDevil As beautiful as a shell
env_conversion.c
Go to the documentation of this file.
1 /* ************************************************************************** */
2 /* */
3 /* ::: :::::::: */
4 /* env_conversion.c :+: :+: :+: */
5 /* +:+ +:+ +:+ */
6 /* By: baelgadi <baelgadi@student.42.fr> +#+ +:+ +#+ */
7 /* +#+#+#+#+#+ +#+ */
8 /* Created: 2025/12/14 01:43:28 by baelgadi #+# #+# */
9 /* Updated: 2026/03/04 04:42:28 by baelgadi ### ########.fr */
10 /* */
11 /* ************************************************************************** */
12 
13 #include "env.h"
14 #include "libft.h"
15 
25 static char *create_env_string(t_env *node)
26 {
27  char *part;
28  char *result;
29 
30  if (!node || !node->key)
31  return (NULL);
32  part = ft_strjoin(node->key, "=");
33  if (!part)
34  return (NULL);
35  if (node->value)
36  result = ft_strjoin(part, node->value);
37  else
38  result = ft_strdup(part);
39  free(part);
40  return (result);
41 }
42 
51 static void free_incomplete_array(char **arr, int count)
52 {
53  int i;
54 
55  i = 0;
56  while (i < count)
57  {
58  free(arr[i]);
59  i++;
60  }
61  free(arr);
62 }
63 
76 static int fill_env_array(char **arr, t_env *env, int size)
77 {
78  t_env *current;
79  int i;
80 
81  current = env;
82  i = 0;
83  while (current && i < size)
84  {
85  arr[i] = create_env_string(current);
86  if (!arr[i])
87  {
88  free_incomplete_array(arr, i);
89  return (0);
90  }
91  current = current->next;
92  i++;
93  }
94  arr[i] = NULL;
95  return (1);
96 }
97 
107 char **env_to_array(t_env *env)
108 {
109  char **arr;
110  int size;
111 
112  if (!env)
113  {
114  arr = ft_calloc(1, sizeof(char *));
115  if (!arr)
116  return (NULL);
117  return (arr);
118  }
119  size = env_list_size(env);
120  arr = ft_calloc(size + 1, sizeof(char *));
121  if (!arr)
122  return (NULL);
123  if (!fill_env_array(arr, env, size))
124  return (NULL);
125  return (arr);
126 }
Environment variable management prototypes.
char ** env_to_array(t_env *env)
Convert the env linked list to a NULL terminated string array.
static void free_incomplete_array(char **arr, int count)
Free a partially filled array.
static char * create_env_string(t_env *node)
Convert an env node to a "KEY=value" string.
static int fill_env_array(char **arr, t_env *env, int size)
Fill an array with KEY=value strings.
int env_list_size(t_env *env_list)
Count the number of nodes in the environment list.
Definition: env_utils.c:91
Environment variable (doubly linked list)
Definition: structs.h:87
char * key
Variable name.
Definition: structs.h:88
char * value
Value (NULL if export only)
Definition: structs.h:89
struct s_env * next
Next node.
Definition: structs.h:90