string splitting function

This commit is contained in:
Ron Pedde 2006-03-20 22:27:56 +00:00
parent 5020ed6884
commit 2fbb744e6f

View File

@ -842,4 +842,52 @@ int conf_isset(char *section, char *key) {
return retval;
}
/**
* split a string on delimiter boundaries, filling
* a string-pointer array.
*
* The user must free both the first element in the array,
* and the array itself.
*
* @param s string to split
* @param delimiters boundaries to split on
* @param argvp an argv array to be filled
* @returns number of tokens
*/
int _conf_split(char *s, char *delimiters, char ***argvp) {
int i;
int numtokens;
const char *snew;
char *t;
char *tokptr;
if ((s == NULL) || (delimiters == NULL) || (argvp == NULL))
return -1;
*argvp = NULL;
snew = s + strspn(s, delimiters);
if ((t = malloc(strlen(snew) + 1)) == NULL)
return -1;
strcpy(t, snew);
numtokens = 0;
tokptr = NULL;
while(strtok_r(t,delimiters,&tokptr) != NULL)
numtokens++;
if ((*argvp = malloc((numtokens + 1)*sizeof(char *))) == NULL) {
free(t);
return -1;
}
if (numtokens == 0)
free(t);
else {
strcpy(t, snew);
tokptr = NULL;
for (i = 0; i < numtokens; i++)
*((*argvp) + i) = strtok_r(t, delimiters, &tokptr);
}
*((*argvp) + numtokens) = NULL;
return numtokens;
}