1 /* Copyright (C) 2002 by  Red Hat, Incorporated. All rights reserved.
2  *
3  * Permission to use, copy, modify, and distribute this software
4  * is freely granted, provided that this notice is preserved.
5  */
6 
7 #define _DEFAULT_SOURCE
8 #include <argz.h>
9 #include <errno.h>
10 #include <sys/types.h>
11 #include <string.h>
12 #include <stdlib.h>
13 
14 error_t
argz_create_sep(const char * string,int sep,char ** argz,size_t * argz_len)15 argz_create_sep (const char *string,
16        int sep,
17        char **argz,
18        size_t *argz_len)
19 {
20   size_t len = 0;
21   int i = 0;
22   int num_strings = 0;
23   char delim[2];
24   char *running = 0;
25   char *old_running = 0;
26   char *token = 0;
27   char *iter = 0;
28 
29   *argz_len = 0;
30 
31   if (!string || string[0] == '\0')
32     {
33       *argz= NULL;
34       return 0;
35     }
36 
37   delim[0] = (char) sep;
38   delim[1] = '\0';
39 
40   running = strdup(string);
41   old_running = running;
42 
43   while ((token = strsep(&running, delim)))
44     {
45       len = strlen(token);
46       *argz_len += (len + 1);
47       num_strings++;
48     }
49 
50   if(!(*argz = (char *)malloc(*argz_len)))
51     return ENOMEM;
52 
53   free(old_running);
54 
55   running = strdup(string);
56   old_running = running;
57 
58   iter = *argz;
59   for (i = 0; i < num_strings; i++)
60     {
61       token = strsep(&running, delim);
62       len = strlen(token) + 1;
63       memcpy(iter, token, len);
64       iter += len;
65     }
66 
67   free(old_running);
68   return 0;
69 }
70