strtok_r.c 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. /* Reentrant string tokenizer. Generic version.
  2. Copyright (C) 1991-2019 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, see
  14. <http://www.gnu.org/licenses/>. */
  15. #ifdef HAVE_CONFIG_H
  16. # include <config.h>
  17. #endif
  18. #include <string.h>
  19. #ifndef _LIBC
  20. /* Get specification. */
  21. # include "strtok_r.h"
  22. # define __strtok_r strtok_r
  23. #endif
  24. /* Parse S into tokens separated by characters in DELIM.
  25. If S is NULL, the saved pointer in SAVE_PTR is used as
  26. the next starting point. For example:
  27. char s[] = "-abc-=-def";
  28. char *sp;
  29. x = strtok_r(s, "-", &sp); // x = "abc", sp = "=-def"
  30. x = strtok_r(NULL, "-=", &sp); // x = "def", sp = NULL
  31. x = strtok_r(NULL, "=", &sp); // x = NULL
  32. // s = "abc\0-def\0"
  33. */
  34. char *
  35. __strtok_r (char *s, const char *delim, char **save_ptr)
  36. {
  37. char *end;
  38. if (s == NULL)
  39. s = *save_ptr;
  40. if (*s == '\0')
  41. {
  42. *save_ptr = s;
  43. return NULL;
  44. }
  45. /* Scan leading delimiters. */
  46. s += strspn (s, delim);
  47. if (*s == '\0')
  48. {
  49. *save_ptr = s;
  50. return NULL;
  51. }
  52. /* Find the end of the token. */
  53. end = s + strcspn (s, delim);
  54. if (*end == '\0')
  55. {
  56. *save_ptr = end;
  57. return s;
  58. }
  59. /* Terminate the token and make *SAVE_PTR point past it. */
  60. *end = '\0';
  61. *save_ptr = end + 1;
  62. return s;
  63. }
  64. #ifdef weak_alias
  65. libc_hidden_def (__strtok_r)
  66. weak_alias (__strtok_r, strtok_r)
  67. #endif