1 /*
2 ** tab.c for  in
3 **
4 ** Made by Pierric
5 ** Login   <pierric@seignobosc.com>
6 **
7 ** Started on  Thu Jan 24 18:36:47 2002 Pierric
8 ** Last update Mon Sep 23 18:02:02 2002 Pierric
9 */
10 #include <stdlib.h>
11 #include <string.h>
12 #include <stdio.h>
13 #include "my_malloc.h"
14 
count_words(char * str,char delim)15 static int		count_words(char *str, char delim)
16 {
17   int                   count;
18 
19   count = 0;
20   while (*str)
21     {
22       if (*str != delim)
23 	{
24 	  count++;
25 	  if (!strchr(str + 1, delim))
26 	    return (count);
27 	  str = strchr(str + 1, delim);
28 	}
29       else
30 	str++;
31     }
32   return (count);
33 }
34 
get_word(char ** str,char delim)35 static char		*get_word(char **str, char delim)
36 {
37   char			*tmp;
38   char			*new;
39 
40   while (**str == delim)
41     (*str)++;
42   if (**str == 0)
43     return (NULL);
44   tmp = strchr(*str, delim);
45   if (!tmp)
46     {
47       new = strdup(*str);
48       while (**str)
49 	(*str)++;
50       return (new);
51     }
52   my_malloc(new, tmp - *str + 1);
53   new[tmp - *str] = '\0';
54   strncpy(new, *str, tmp - *str);
55   *str = tmp;
56   return (new);
57 }
58 
tab_free(char ** tab)59 void			tab_free(char **tab)
60 {
61   int                   index;
62 
63   if (!tab)
64     return;
65   for (index = 0; tab[index]; index++)
66     free(tab[index]);
67   free(tab);
68 }
69 
tab_fill(char * str,char delim)70 char			**tab_fill(char *str, char delim)
71 {
72   int                   count;
73   char                  **tab;
74   int                   index;
75 
76   if (!str)
77     return (NULL);
78   count = count_words(str, delim);
79   if (!count)
80     return (NULL);
81   my_malloc(tab, (count + 1) * sizeof(char *));
82   for (index = 0; (tab[index] = get_word(&str, delim)); index++)
83     ;
84   return (tab);
85 }
86 
87 /*
88 **		Deletes the first element of a wordtab, shifting the other
89 **	elements. The size of the malloced area stays the same, though
90 */
tab_delete_first(char ** tab)91 int			tab_delete_first(char **tab)
92 {
93   int                   i;
94 
95   if (!tab[0])
96     return (-1);
97   free(tab[0]);
98   for (i = 0; tab[i]; i++)
99     tab[i] = tab[i + 1];
100   return (0);
101 }
102 
tab_count_words(char ** tab)103 int			tab_count_words(char **tab)
104 {
105   int                   count;
106 
107   if (!tab)
108     return (0);
109   for (count = 0; tab[count]; count++)
110     ;
111   return (count);
112 }
113