strtok_r.c 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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, see
  14. <http://www.gnu.org/licenses/>. */
  15. #include <string.h>
  16. #ifdef __USE_GNU
  17. # define __rawmemchr rawmemchr
  18. #else
  19. # define __rawmemchr strchr
  20. #endif
  21. #if 0
  22. Parse S into tokens separated by characters in DELIM.
  23. If S is NULL, the saved pointer in SAVE_PTR is used as
  24. the next starting point. For example:
  25. char s[] = "-abc-=-def";
  26. char *sp;
  27. x = strtok_r(s, "-", &sp); /* x = "abc", sp = "=-def" */
  28. x = strtok_r(NULL, "-=", &sp); /* x = "def", sp = NULL */
  29. x = strtok_r(NULL, "=", &sp); /* x = NULL */
  30. /* s = "abc\0-def\0" */
  31. #endif
  32. char *strtok_r (char *s, const char *delim, char **save_ptr)
  33. {
  34. char *token;
  35. if (s == NULL)
  36. s = *save_ptr;
  37. /* Scan leading delimiters. */
  38. s += strspn (s, delim);
  39. if (*s == '\0')
  40. {
  41. *save_ptr = s;
  42. return NULL;
  43. }
  44. /* Find the end of the token. */
  45. token = s;
  46. s = strpbrk (token, delim);
  47. if (s == NULL)
  48. /* This token finishes the string. */
  49. *save_ptr = __rawmemchr (token, '\0');
  50. else
  51. {
  52. /* Terminate the token and make *SAVE_PTR point past it. */
  53. *s = '\0';
  54. *save_ptr = s + 1;
  55. }
  56. return token;
  57. }
  58. libc_hidden_def(strtok_r)