strtok_r是linux平台下的strtok函数的线程安全版。windows的string.h中并不包含它。要想使用这个函数,上网搜其linux下的实现源码,复制到你的程序中即可。别的方式应该也有,比如使用GNU C Library。我下载了GNU C Library,在其源代码中找到了strtok_r的实现代码,复制过来。
strtok和strtok_r的源代码
这两个函数的实现,由众多的版本。我strtok_r来自于GNU C Library,strtok则调用了strtok_r。因此先给出strtok_r的源代码。
- /*
- * strtok_r.c:
- * Implementation of strtok_r for systems which don't have it.
- *
- * This is taken from the GNU C library and is distributed under the terms of
- * the LGPL. See copyright notice below.
- *
- */
- #ifdef HAVE_CONFIG_H
- #include "configuration.h"
- #endif /* HAVE_CONFIG_H */
- #ifndef HAVE_STRTOK_R
- static const char rcsid[] = "$Id: strtok_r.c,v 1.1 2001/04/24 14:25:34 chris Exp $";
- #include <string.h>
- #undef strtok_r
- /* Parse S into tokens separated by characters in DELIM.
- If S is NULL, the saved pointer in SAVE_PTR is used as
- the next starting point. For example:
- char s[] = "-abc-=-def";
- char *sp;
- x = strtok_r(s, "-", &sp); // x = "abc", sp = "=-def"
- x = strtok_r(NULL, "-=", &sp); // x = "def", sp = NULL
- x = strtok_r(NULL, "=", &sp); // x = NULL
- // s = "abc/0-def/0"
- */
- char *strtok_r(char *s, const char *delim, char **save_ptr) {
- char *token;
- if (s == NULL) s = *save_ptr;
- /* Scan leading delimiters. */
- s += strspn(s, delim);
- if (*s == '/0')
- return NULL;
- /* Find the end of the token. */
- token = s;
- s = strpbrk(token, delim);
- if (s == NULL)
- /* This token finishes the string. */
- *save_ptr = strchr(token, '/0');
- else {
- /* Terminate the token and make *SAVE_PTR point past it. */
- *s = '/0';
- *save_ptr = s + 1;
- }
- return token;
- }
代码整体的流程如下:
(1)判断参数s是否为NULL,如果是NULL就以传递进来的save_ptr作为起始分解位置;若不是NULL,则以s开始切分。
(2)跳过待分解字符串开始的所有分界符。
(3)判断当前待分解的位置是否为'/0',若是则返回NULL(联系到(一)中所说对返回值为NULL的解释);不是则继续。
(4)保存当前的待分解串的指针token,调用strpbrk在token中找分界符:如果找不到,则将save_ptr赋值为待分解串尾部'/0'所在的位置,token没有发生变化;若找的到则将分界符所在位置赋值为'/0',token相当于被截断了(提取出来),save_ptr指向分界符的下一位。
(5)函数的最后(无论找到还是没找到)都将返回。
对于函数strtok来说,可以理解为用一个内部的静态变量将strtok_r中的save_ptr给保存起来,对调用者不可见。其代码如下:
- char *strtok(char *s, const char *delim)
- {
- static char *last;
- return strtok_r(s, delim, &last);
- }
有了上述两个函数的实现代码,再理解(一)(二)中所讲的一些要点也就不困难了。
花那么多篇幅总结这两个函数,一来是因为很对人对于strtok的误解比较深,网上很少有对于其非常详细的讨论,因此总结一份比较全面的材料,是有必要的;二来这也是自己不断学习的一个过程,总结会得到远比两个函数重要很多的信息。