Last active
April 17, 2019 16:58
-
-
Save kala13x/20ee37e9a4c3d094d9ac to your computer and use it in GitHub Desktop.
Thread safe alternative of the strtok() function
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
/* | |
* strtoken.c | |
* | |
* Copyleft (C) 2015 Sun Dro (a.k.a. kala13x) | |
* | |
* This source is thread safe alternative of the strtok(). | |
* See usage of the get_token() below at main() function. | |
*/ | |
#include <stdio.h> | |
#include <stdlib.h> | |
#include <string.h> | |
/* | |
* get_token() - Function breaks a string into a sequence of zero or more | |
* nonempty tokens. On the first call to get_token() func the string to be | |
* parsed should be specified in psrc. In each subsequent call that should | |
* parse the same string, psrc must be NULL. The delimit argument specifies | |
* a set of bytes that delimit the tokens in the parsed string. Functions | |
* return a pointer to the next token, or NULL if there are no more tokens. | |
*/ | |
char *get_token(char *psrc, const char *delimit, void *psave) | |
{ | |
static char sret[512]; | |
register char *ptr = psave; | |
memset(sret, 0, sizeof(sret)); | |
if (psrc != NULL) strcpy(ptr, psrc); | |
if (ptr == NULL) return NULL; | |
int i = 0, nlength = strlen(ptr); | |
for (i = 0; i < nlength; i++) | |
{ | |
if (ptr[i] == delimit[0]) break; | |
if (ptr[i] == delimit[1]) | |
{ | |
ptr = NULL; | |
break; | |
} | |
sret[i] = ptr[i]; | |
} | |
if (ptr != NULL) strcpy(ptr, &ptr[i+1]); | |
return sret; | |
} | |
int main(int argc, char *argv[]) | |
{ | |
char string[32]; | |
char saveptr[32]; | |
char delimit[2] = {':', '\0'}; | |
strcpy(string, "first:second:third"); | |
char *ptr = get_token(string, delimit, &saveptr); | |
printf("1: %s\n", ptr); | |
ptr = get_token(NULL, delimit, &saveptr); | |
printf("2: %s\n", ptr); | |
ptr = get_token(NULL, delimit, &saveptr); | |
printf("3: %s\n", ptr); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment