strtok_r.c 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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. #include <string.h>
  17. libc_hidden_proto(strtok_r)
  18. libc_hidden_proto(strspn)
  19. libc_hidden_proto(strpbrk)
  20. #ifdef __USE_GNU
  21. # define __rawmemchr rawmemchr
  22. libc_hidden_proto(rawmemchr)
  23. #else
  24. # define __rawmemchr strchr
  25. libc_hidden_proto(strchr)
  26. #endif
  27. /* Parse S into tokens separated by characters in DELIM.
  28. If S is NULL, the saved pointer in SAVE_PTR is used as
  29. the next starting point. For example:
  30. char s[] = "-abc-=-def";
  31. char *sp;
  32. x = strtok_r(s, "-", &sp); // x = "abc", sp = "=-def"
  33. x = strtok_r(NULL, "-=", &sp); // x = "def", sp = NULL
  34. x = strtok_r(NULL, "=", &sp); // x = NULL
  35. // s = "abc\0-def\0"
  36. */
  37. char *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. libc_hidden_def(strtok_r)