Back to index

glibc  2.9
strtok_r.c
Go to the documentation of this file.
00001 /* Reentrant string tokenizer.  Generic version.
00002    Copyright (C) 1991,1996-1999,2001,2004 Free Software Foundation, Inc.
00003    This file is part of the GNU C Library.
00004 
00005    The GNU C Library is free software; you can redistribute it and/or
00006    modify it under the terms of the GNU Lesser General Public
00007    License as published by the Free Software Foundation; either
00008    version 2.1 of the License, or (at your option) any later version.
00009 
00010    The GNU C Library is distributed in the hope that it will be useful,
00011    but WITHOUT ANY WARRANTY; without even the implied warranty of
00012    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
00013    Lesser General Public License for more details.
00014 
00015    You should have received a copy of the GNU Lesser General Public
00016    License along with the GNU C Library; if not, write to the Free
00017    Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
00018    02111-1307 USA.  */
00019 
00020 #ifdef HAVE_CONFIG_H
00021 # include <config.h>
00022 #endif
00023 
00024 #include <string.h>
00025 
00026 #undef strtok_r
00027 #undef __strtok_r
00028 
00029 #ifndef _LIBC
00030 /* Get specification.  */
00031 # include "strtok_r.h"
00032 # define __strtok_r strtok_r
00033 # define __rawmemchr strchr
00034 #endif
00035 
00036 /* Parse S into tokens separated by characters in DELIM.
00037    If S is NULL, the saved pointer in SAVE_PTR is used as
00038    the next starting point.  For example:
00039        char s[] = "-abc-=-def";
00040        char *sp;
00041        x = strtok_r(s, "-", &sp);  // x = "abc", sp = "=-def"
00042        x = strtok_r(NULL, "-=", &sp);     // x = "def", sp = NULL
00043        x = strtok_r(NULL, "=", &sp);      // x = NULL
00044               // s = "abc\0-def\0"
00045 */
00046 char *
00047 __strtok_r (char *s, const char *delim, char **save_ptr)
00048 {
00049   char *token;
00050 
00051   if (s == NULL)
00052     s = *save_ptr;
00053 
00054   /* Scan leading delimiters.  */
00055   s += strspn (s, delim);
00056   if (*s == '\0')
00057     {
00058       *save_ptr = s;
00059       return NULL;
00060     }
00061 
00062   /* Find the end of the token.  */
00063   token = s;
00064   s = strpbrk (token, delim);
00065   if (s == NULL)
00066     /* This token finishes the string.  */
00067     *save_ptr = __rawmemchr (token, '\0');
00068   else
00069     {
00070       /* Terminate the token and make *SAVE_PTR point past it.  */
00071       *s = '\0';
00072       *save_ptr = s + 1;
00073     }
00074   return token;
00075 }
00076 #ifdef weak_alias
00077 libc_hidden_def (__strtok_r)
00078 weak_alias (__strtok_r, strtok_r)
00079 #endif