Last active
December 15, 2015 01:59
-
-
Save fenollp/5183540 to your computer and use it in GitHub Desktop.
A use case of strtok_r (instead of strtok) to split a string str wrt ifs characters.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
char **ifs_split(const char *str, const char *ifs) | |
{ | |
size_t index = 0; | |
size_t size = 1; | |
char *segment = NULL; | |
char *start = NULL; | |
char *rest = NULL; | |
char **tab = NULL; // Thou shall free thee. | |
start = dupstr(str); | |
tab = calloc(1, sizeof (char *)); | |
if (NULL == tab) | |
return NULL; | |
segment = strtok_r(start, ifs, &rest); | |
do | |
tab = append_str(segment, tab, &index, &size); | |
while (NULL != (segment = strtok_r(rest, ifs, &rest))); | |
free(start); | |
return tab; // Is NULL-terminated. | |
} | |
/* dupstr is my strdup. If you don't see what append_str() does */ | |
char **append_str(const char *str, char **tab, | |
size_t *index, size_t *size) | |
{ | |
char **tmp = tab; | |
if (*index + 1 >= *size) | |
{ | |
tmp = realloc(tab, (*size *= 2) * sizeof (char *)); | |
if (NULL == tmp) | |
{ | |
free(tab); | |
return NULL; | |
} | |
} | |
tmp[*index] = dupstr(str); | |
tmp[++(*index)] = NULL; | |
return tmp; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment