strtok_r.c 2.1 KB

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