strtok_r.c 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. /* Reentrant string tokenizer. Generic version.
  2. Copyright (C) 1991,1996-1999,2001,2004 Free Software Foundation, Inc.
  3. This file is part of the GNU C Library.
  4. The GNU C Library is free software; you can redistribute it and/or
  5. modify it under the terms of the GNU Lesser General Public
  6. License as published by the Free Software Foundation; either
  7. version 2.1 of the License, or (at your option) any later version.
  8. The GNU C Library is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  11. Lesser General Public License for more details.
  12. You should have received a copy of the GNU Lesser General Public
  13. License along with the GNU C Library; if not, write to the Free
  14. Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
  15. 02111-1307 USA. */
  16. #define _GNU_SOURCE
  17. #include <string.h>
  18. #undef strtok_r
  19. #undef __strtok_r
  20. /* Parse S into tokens separated by characters in DELIM.
  21. If S is NULL, the saved pointer in SAVE_PTR is used as
  22. the next starting point. For example:
  23. char s[] = "-abc-=-def";
  24. char *sp;
  25. x = strtok_r(s, "-", &sp); // x = "abc", sp = "=-def"
  26. x = strtok_r(NULL, "-=", &sp); // x = "def", sp = NULL
  27. x = strtok_r(NULL, "=", &sp); // x = NULL
  28. // s = "abc\0-def\0"
  29. */
  30. char *
  31. __strtok_r (s, delim, save_ptr)
  32. char *s;
  33. const char *delim;
  34. char **save_ptr;
  35. {
  36. char *token;
  37. if (s == NULL)
  38. s = *save_ptr;
  39. /* Scan leading delimiters. */
  40. s += strspn (s, delim);
  41. if (*s == '\0')
  42. {
  43. *save_ptr = s;
  44. return NULL;
  45. }
  46. /* Find the end of the token. */
  47. token = s;
  48. s = strpbrk (token, delim);
  49. if (s == NULL)
  50. /* This token finishes the string. */
  51. *save_ptr = rawmemchr (token, '\0');
  52. else
  53. {
  54. /* Terminate the token and make *SAVE_PTR point past it. */
  55. *s = '\0';
  56. *save_ptr = s + 1;
  57. }
  58. return token;
  59. }
  60. weak_alias (__strtok_r, strtok_r)