Skip to content

Instantly share code, notes, and snippets.

@fenollp
Last active December 15, 2015 01:59
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fenollp/5183540 to your computer and use it in GitHub Desktop.
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.
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