The C/C++ function strtok_r() is the thread safe version of the strtok() function, and is part of the string.h string manipulation library.

char *strtok_r(char *s, const char *delim, char **ptrptr);

strtok_r() is used almost exactly as strtok() with one minor exception. In addition to the string buffer and delimiter string, a char ** variable is passed. This is used internally to keep track of multiple strtok_r's going on at once. Using it is very simple.

char* util = 0;
char* sptr;
char buffer = "This is a test\n";
char tokens = "s\n";

/* First call has the first argument of the string to examine */
util = strtok_r( buffer, tokens, &sptr );
do 
{
   printf( "Token = '%s'\n", util );
}
while( util = strtok_r( NULL, tokens, &sptr ));

This code results in:
Token = 'Thi'
Token = ' i'
Token = ' a te'
Token = 't'

If the above example were to be embedded within a larger loop doing string parsing as well, and using strtok_r(), all would be well, assuming that you are using a different variable for sptr.

Log in or register to write something here or to contact authors.