What's the difference between strtok
and strtok_r
in C
and when are we supposed to use which?
The C function strtok() is a string tokenization function that takes two arguments: an initial string to be parsed and a const -qualified character delimiter. It returns a pointer to the first character of a token or to a null pointer if there is no token.
Practical Application: strtok can be used to split a string in multiple strings based on some separators. A simple CSV file support might be implemented using this function.
strtok is neither thread safe nor re-entrant because it uses a static buffer while parsing. This means that if a function calls strtok , no function that it calls while it is using strtok can also use strtok , and it cannot be called by any function that is itself using strtok .
It is important to not that strtok does not allocate memory and create new strings for each of the tokens it finds. All the data still resides in the original string. Whenever strtok is called, it continues from where it left off and skips separators until it gets a valid character.
strtok
is equivalent to (and often defined as):
char *strtok(char *str, const char *delim) { static char *save; return strtok_r(str, delim, &save); }
in general, you should use strtok_r
directly rather than strtok
, unless you need to make your code portable to pre-POSIX-2001 systems that only support strtok
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With