strtok_r.c 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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. /* Parse S into tokens separated by characters in DELIM.
  19. If S is NULL, the saved pointer in SAVE_PTR is used as
  20. the next starting point. For example:
  21. char s[] = "-abc-=-def";
  22. char *sp;
  23. x = strtok_r(s, "-", &sp); // x = "abc", sp = "=-def"
  24. x = strtok_r(NULL, "-=", &sp); // x = "def", sp = NULL
  25. x = strtok_r(NULL, "=", &sp); // x = NULL
  26. // s = "abc\0-def\0"
  27. */
  28. char attribute_hidden *__strtok_r (char *s, const char *delim, char **save_ptr)
  29. {
  30. char *token;
  31. if (s == NULL)
  32. s = *save_ptr;
  33. /* Scan leading delimiters. */
  34. s += __strspn (s, delim);
  35. if (*s == '\0')
  36. {
  37. *save_ptr = s;
  38. return NULL;
  39. }
  40. /* Find the end of the token. */
  41. token = s;
  42. s = __strpbrk (token, delim);
  43. if (s == NULL)
  44. /* This token finishes the string. */
  45. *save_ptr = __rawmemchr (token, '\0');
  46. else
  47. {
  48. /* Terminate the token and make *SAVE_PTR point past it. */
  49. *s = '\0';
  50. *save_ptr = s + 1;
  51. }
  52. return token;
  53. }
  54. strong_alias(__strtok_r,strtok_r)