Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > C Programming > strtok and strtok_r

Reply
Thread Tools

strtok and strtok_r

 
 
siddhu
Guest
Posts: n/a
 
      09-14-2007
Dear experts,

As I know strtok_r is re-entrant version of strtok.
strtok_r() is called with s1(lets say) as its first parameter.
Remaining tokens from s1 are obtained by calling strtok_r() with a
null pointer for the first parameter.
My confusion is that this behavior is same as strtok. So I assume
strtok_r must also be using any function static variable to keep the
information about s1. If this is the case then how strtok_r is re-
entrant?
Otherwise how it keeps the information about s1?

Regards,
Siddharth

 
Reply With Quote
 
 
 
 
jacob navia
Guest
Posts: n/a
 
      09-14-2007
siddhu wrote:
> Dear experts,
>
> As I know strtok_r is re-entrant version of strtok.
> strtok_r() is called with s1(lets say) as its first parameter.
> Remaining tokens from s1 are obtained by calling strtok_r() with a
> null pointer for the first parameter.
> My confusion is that this behavior is same as strtok. So I assume
> strtok_r must also be using any function static variable to keep the
> information about s1. If this is the case then how strtok_r is re-
> entrant?
> Otherwise how it keeps the information about s1?
>
> Regards,
> Siddharth
>


The reentrant version takes one more argument where it stores its progress:
http://www.bullfreeware.com/download...-1.0.9/support
// Skip GNU copyright
#include <string.h>
/* Parse S into tokens separated by characters in DELIM.
If S is NULL, the saved pointer in SAVE_PTR is used as
the next starting point. For example:
char s[] = "-abc-=-def";
char *sp;
x = strtok_r(s, "-", &sp); // x = "abc", sp = "=-def"
x = strtok_r(NULL, "-=", &sp); // x = "def", sp = NULL
x = strtok_r(NULL, "=", &sp); // x = NULL
// s = "abc\0-def\0"
*/
char *strtok_r (char *s,
const char *delim,
char **save_ptr)
{
char *token;

if (s == NULL)
s = *save_ptr;

/* Scan leading delimiters. */
s += strspn (s, delim);
if (*s == '\0')
return NULL;

/* Find the end of the token. */
token = s;
s = strpbrk (token, delim);
if (s == NULL)
/* This token finishes the string. */
*save_ptr = strchr (token, '\0');
else
{
/* Terminate the token and make *SAVE_PTR point past it. */
*s = '\0';
*save_ptr = s + 1;
}
return token;
}
 
Reply With Quote
 
 
 
 
Ben Pfaff
Guest
Posts: n/a
 
      09-14-2007
siddhu <(E-Mail Removed)> writes:

> As I know strtok_r is re-entrant version of strtok.


This is true on a system compliant with, e.g., POSIX, but it is
not required by C. Followups set.

> [...misunderstanding...]


I think the problem is that you do not realize that strtok_r
takes one more parameter than strtok, and uses that parameter to
save state from one call to the next.
--
char a[]="\n .CJacehknorstu";int putchar(int);int main(void){unsigned long b[]
={0x67dffdff,0x9aa9aa6a,0xa77ffda9,0x7da6aa6a,0xa6 7f6aaa,0xaa9aa9f6,0x11f6},*p
=b,i=24;for(;p+=!*p;*p/=4)switch(0[p]&3)case 0:{return 0;for(p--;i--;i--)case+
2:{i++;if(i)break;else default:continue;if(0)case 1utchar(a[i&15]);break;}}}
 
Reply With Quote
 
Charlie Gordon
Guest
Posts: n/a
 
      09-14-2007
"siddhu" <(E-Mail Removed)> a écrit dans le message de news:
(E-Mail Removed) om...
> Dear experts,
>
> As I know strtok_r is re-entrant version of strtok.
> strtok_r() is called with s1(lets say) as its first parameter.
> Remaining tokens from s1 are obtained by calling strtok_r() with a
> null pointer for the first parameter.
> My confusion is that this behavior is same as strtok. So I assume
> strtok_r must also be using any function static variable to keep the
> information about s1. If this is the case then how strtok_r is re-
> entrant?
> Otherwise how it keeps the information about s1?


strtok_r takes an extra parameter, q pointer to a char * where it stores its
current state.

The implementation is quite straightforward:

char *strtok_r(char *str, const char *delim, char **nextp)
{
char *ret;

if (str == NULL)
str = *nextp;
str += strspn(str, delim);
if (*str == '\0')
return NULL;
ret = str;
str += strcspn(str, delim);
if (*str)
*str++ = '\0';
*nextp = str;
return ret;
}

--
Chqrlie.


 
Reply With Quote
 
CBFalconer
Guest
Posts: n/a
 
      09-14-2007
siddhu wrote:
>
> As I know strtok_r is re-entrant version of strtok.
> strtok_r() is called with s1(lets say) as its first parameter.
> Remaining tokens from s1 are obtained by calling strtok_r() with
> a null pointer for the first parameter. My confusion is that
> this behavior is same as strtok. So I assume strtok_r must also
> be using any function static variable to keep the information
> about s1. If this is the case then how strtok_r is re- entrant?
> Otherwise how it keeps the information about s1?


There is no such standard C function as strtok_r(). To discuss
such a function you have to give its source, in standard C.
However, I just happen to have a suitable replacement function
lying about, whose source follows:

/* ------- file tknsplit.c ----------*/
#include "tknsplit.h"

/* copy over the next tkn from an input string, after
skipping leading blanks (or other whitespace?). The
tkn is terminated by the first appearance of tknchar,
or by the end of the source string.

The caller must supply sufficient space in tkn to
receive any tkn, Otherwise tkns will be truncated.

Returns: a pointer past the terminating tknchar.

This will happily return an infinity of empty tkns if
called with src pointing to the end of a string. Tokens
will never include a copy of tknchar.

A better name would be "strtkn", except that is reserved
for the system namespace. Change to that at your risk.

released to Public Domain, by C.B. Falconer.
Published 2006-02-20. Attribution appreciated.
Revised 2006-06-13 2007-05-26 (name)
*/

const char *tknsplit(const char *src, /* Source of tkns */
char tknchar, /* tkn delimiting char */
char *tkn, /* receiver of parsed tkn */
size_t lgh) /* length tkn can receive */
/* not including final '\0' */
{
if (src) {
while (' ' == *src) src++;

while (*src && (tknchar != *src)) {
if (lgh) {
*tkn++ = *src;
--lgh;
}
src++;
}
if (*src && (tknchar == *src)) src++;
}
*tkn = '\0';
return src;
} /* tknsplit */

#ifdef TESTING
#include <stdio.h>

#define ABRsize 6 /* length of acceptable tkn abbreviations */

/* ---------------- */

static void showtkn(int i, char *tok)
{
putchar(i + '1'); putchar(':');
puts(tok);
} /* showtkn */

/* ---------------- */

int main(void)
{
char teststring[] = "This is a test, ,, abbrev, more";

const char *t, *s = teststring;
int i;
char tkn[ABRsize + 1];

puts(teststring);
t = s;
for (i = 0; i < 4; i++) {
t = tknsplit(t, ',', tkn, ABRsize);
showtkn(i, tkn);
}

puts("\nHow to detect 'no more tkns' while truncating");
t = s; i = 0;
while (*t) {
t = tknsplit(t, ',', tkn, 3);
showtkn(i, tkn);
i++;
}

puts("\nUsing blanks as tkn delimiters");
t = s; i = 0;
while (*t) {
t = tknsplit(t, ' ', tkn, ABRsize);
showtkn(i, tkn);
i++;
}
return 0;
} /* main */

#endif
/* ------- end file tknsplit.c ----------*/

/* ------- file tknsplit.h ----------*/
#ifndef H_tknsplit_h
# define H_tknsplit_h

# ifdef __cplusplus
extern "C" {
# endif

#include <stddef.h>

/* copy over the next tkn from an input string, after
skipping leading blanks (or other whitespace?). The
tkn is terminated by the first appearance of tknchar,
or by the end of the source string.

The caller must supply sufficient space in tkn to
receive any tkn, Otherwise tkns will be truncated.

Returns: a pointer past the terminating tknchar.

This will happily return an infinity of empty tkns if
called with src pointing to the end of a string. Tokens
will never include a copy of tknchar.

released to Public Domain, by C.B. Falconer.
Published 2006-02-20. Attribution appreciated.
revised 2007-05-26 (name)
*/

const char *tknsplit(const char *src, /* Source of tkns */
char tknchar, /* tkn delimiting char */
char *tkn, /* receiver of parsed tkn */
size_t lgh); /* length tkn can receive */
/* not including final '\0' */

# ifdef __cplusplus
}
# endif
#endif
/* ------- end file tknsplit.h ----------*/

--
Chuck F (cbfalconer at maineline dot net)
Available for consulting/temporary embedded and systems.
<http://cbfalconer.home.att.net>



--
Posted via a free Usenet account from http://www.teranews.com

 
Reply With Quote
 
Charlie Gordon
Guest
Posts: n/a
 
      09-14-2007
"CBFalconer" <(E-Mail Removed)> a écrit dans le message de news:
(E-Mail Removed)...
> siddhu wrote:
>>
>> As I know strtok_r is re-entrant version of strtok.
>> strtok_r() is called with s1(lets say) as its first parameter.
>> Remaining tokens from s1 are obtained by calling strtok_r() with
>> a null pointer for the first parameter. My confusion is that
>> this behavior is same as strtok. So I assume strtok_r must also
>> be using any function static variable to keep the information
>> about s1. If this is the case then how strtok_r is re- entrant?
>> Otherwise how it keeps the information about s1?

>
> There is no such standard C function as strtok_r(). To discuss
> such a function you have to give its source, in standard C.
> However, I just happen to have a suitable replacement function
> lying about, whose source follows:


Come on, strtok_r is part of POSIX. Do you pretend POSIX is not popular
enough.
Multiple implementations of strtok_r have been posted before your answer.

>
> /* ------- file tknsplit.c ----------*/
> #include "tknsplit.h"
>
> /* copy over the next tkn from an input string, after
> skipping leading blanks (or other whitespace?). The


Why skip blanks ? this is not strtok behaviour.
The code and the comment don't agree on what blanks are: by C99 Standard,
blanks are space and tab.

> tkn is terminated by the first appearance of tknchar,
> or by the end of the source string.


Your function definitely differs a lot from strtok that takes a collection
of delimiters instead of a single char.

> The caller must supply sufficient space in tkn to
> receive any tkn, Otherwise tkns will be truncated.
>
> Returns: a pointer past the terminating tknchar.
>
> This will happily return an infinity of empty tkns if
> called with src pointing to the end of a string. Tokens
> will never include a copy of tknchar.


again, this is not the behaviour of strtok: sequences of separators are
considered one.

> A better name would be "strtkn", except that is reserved
> for the system namespace. Change to that at your risk.
>
> released to Public Domain, by C.B. Falconer.
> Published 2006-02-20. Attribution appreciated.
> Revised 2006-06-13 2007-05-26 (name)
> */
>
> const char *tknsplit(const char *src, /* Source of tkns */
> char tknchar, /* tkn delimiting char */
> char *tkn, /* receiver of parsed tkn */
> size_t lgh) /* length tkn can receive */
> /* not including final '\0' */


I have reservations about your API:
- instead of returning a const char *, you should return the number of chars
skipped.
it would prevent const poisonning when you pass a regular char * but cannot
store the return value into the same variable... It would also allow
trivial testing of end of string.
- the lgh parameter should be the size of the destination array
(sizeof(buf)), out of consistency with other C library functions such as
snprintf, and to avoid off by one errors: if callers pass sizeof(destbuf) -
1, they wouln't invoke UB, whereas they would by passing sizeof(destbuf)
with your current semantics.

> {
> if (src) {
> while (' ' == *src) src++;
>
> while (*src && (tknchar != *src)) {
> if (lgh) {
> *tkn++ = *src;
> --lgh;
> }
> src++;
> }
> if (*src && (tknchar == *src)) src++;
> }
> *tkn = '\0';
> return src;
> } /* tknsplit */
>
> #ifdef TESTING
> #include <stdio.h>
>
> #define ABRsize 6 /* length of acceptable tkn abbreviations */
>
> /* ---------------- */
>
> static void showtkn(int i, char *tok)
> {
> putchar(i + '1'); putchar(':');
> puts(tok);
> } /* showtkn */
>
> /* ---------------- */
>
> int main(void)
> {
> char teststring[] = "This is a test, ,, abbrev, more";
>
> const char *t, *s = teststring;
> int i;
> char tkn[ABRsize + 1];
>
> puts(teststring);
> t = s;
> for (i = 0; i < 4; i++) {
> t = tknsplit(t, ',', tkn, ABRsize);
> showtkn(i, tkn);
> }
>
> puts("\nHow to detect 'no more tkns' while truncating");
> t = s; i = 0;
> while (*t) {
> t = tknsplit(t, ',', tkn, 3);
> showtkn(i, tkn);
> i++;
> }
>
> puts("\nUsing blanks as tkn delimiters");
> t = s; i = 0;
> while (*t) {
> t = tknsplit(t, ' ', tkn, ABRsize);
> showtkn(i, tkn);
> i++;
> }
> return 0;
> } /* main */
>
> #endif
> /* ------- end file tknsplit.c ----------*/
>
> /* ------- file tknsplit.h ----------*/
> #ifndef H_tknsplit_h
> # define H_tknsplit_h
>
> # ifdef __cplusplus
> extern "C" {
> # endif
>
> #include <stddef.h>
>
> /* copy over the next tkn from an input string, after
> skipping leading blanks (or other whitespace?). The
> tkn is terminated by the first appearance of tknchar,
> or by the end of the source string.
>
> The caller must supply sufficient space in tkn to
> receive any tkn, Otherwise tkns will be truncated.
>
> Returns: a pointer past the terminating tknchar.
>
> This will happily return an infinity of empty tkns if
> called with src pointing to the end of a string. Tokens
> will never include a copy of tknchar.
>
> released to Public Domain, by C.B. Falconer.
> Published 2006-02-20. Attribution appreciated.
> revised 2007-05-26 (name)
> */
>
> const char *tknsplit(const char *src, /* Source of tkns */
> char tknchar, /* tkn delimiting char */
> char *tkn, /* receiver of parsed tkn */
> size_t lgh); /* length tkn can receive */
> /* not including final '\0' */
>
> # ifdef __cplusplus
> }
> # endif
> #endif
> /* ------- end file tknsplit.h ----------*/


Posting the source code to a public version strtok_r would have been more
helpful.
The only advantage your function offers over strtok_r is the fact that it
does not modify the source string.

--
Chqrlie.


 
Reply With Quote
 
Martien verbruggen
Guest
Posts: n/a
 
      09-15-2007
On Sat, 15 Sep 2007 01:07:48 +0200,
Charlie Gordon <(E-Mail Removed)> wrote:
> "CBFalconer" <(E-Mail Removed)> a écrit dans le message de news:
> (E-Mail Removed)...
>> siddhu wrote:
>>>
>>> As I know strtok_r is re-entrant version of strtok.


[snip]

>> There is no such standard C function as strtok_r(). To discuss
>> such a function you have to give its source, in standard C.
>> However, I just happen to have a suitable replacement function
>> lying about, whose source follows:

>
> Come on, strtok_r is part of POSIX. Do you pretend POSIX is not popular
> enough.


POSIX is very popular. So is cricket. Neither, however is topical here.

If there were no other place where POSIX were already discussed, one
would have been created, given its popularity.

POSIX is discussed on comp.unix.programmer, and the people there are
very knowledgeable about the subject.

Regards,
Martien
--
|
Martien Verbruggen | Failure is not an option. It comes bundled
| with your Microsoft product.
|
 
Reply With Quote
 
CBFalconer
Guest
Posts: n/a
 
      09-15-2007
Charlie Gordon wrote:
> "CBFalconer" <(E-Mail Removed)> a écrit:
>> siddhu wrote:
>>>
>>> As I know strtok_r is re-entrant version of strtok.
>>> strtok_r() is called with s1(lets say) as its first parameter.
>>> Remaining tokens from s1 are obtained by calling strtok_r() with
>>> a null pointer for the first parameter. My confusion is that
>>> this behavior is same as strtok. So I assume strtok_r must also
>>> be using any function static variable to keep the information
>>> about s1. If this is the case then how strtok_r is re- entrant?
>>> Otherwise how it keeps the information about s1?

>>
>> There is no such standard C function as strtok_r(). To discuss
>> such a function you have to give its source, in standard C.
>> However, I just happen to have a suitable replacement function
>> lying about, whose source follows:

>
> Come on, strtok_r is part of POSIX. Do you pretend POSIX is not
> popular enough. Multiple implementations of strtok_r have been
> posted before your answer.


Popularity doesn't enter into it. Presence in the standard library
does. strtok_r doesn't exist there. That makes it off-topic here
in c.l.c. (barring source).

>>
>> /* ------- file tknsplit.c ----------*/
>> #include "tknsplit.h"
>>
>> /* copy over the next tkn from an input string, after
>> skipping leading blanks (or other whitespace?). The

>
> Why skip blanks ? this is not strtok behaviour. The code and the
> comment don't agree on what blanks are: by C99 Standard, blanks are
> space and tab.


This is not strtok. It is tknsplit. This is behaviour that seems
more useful to me. You don't have to use it, but siddhu may wish
to.

>

.... snip ...
>
> Posting the source code to a public version strtok_r would have
> been more helpful. The only advantage your function offers over
> strtok_r is the fact that it does not modify the source string.


Which, IMO, is a major improvement. It also detects missing
tokens. It (once more) is NOT strtok. I have no idea what
strtok_r is, except that it invades user namespace.

--
Chuck F (cbfalconer at maineline dot net)
Available for consulting/temporary embedded and systems.
<http://cbfalconer.home.att.net>



--
Posted via a free Usenet account from http://www.teranews.com

 
Reply With Quote
 
Charlie Gordon
Guest
Posts: n/a
 
      09-15-2007
"Martien verbruggen" <(E-Mail Removed)> a écrit dans le message de
news: (E-Mail Removed)...
> On Sat, 15 Sep 2007 01:07:48 +0200,
> Charlie Gordon <(E-Mail Removed)> wrote:
>> "CBFalconer" <(E-Mail Removed)> a écrit dans le message de news:
>> (E-Mail Removed)...
>>> siddhu wrote:
>>>>
>>>> As I know strtok_r is re-entrant version of strtok.

>
> [snip]
>
>>> There is no such standard C function as strtok_r(). To discuss
>>> such a function you have to give its source, in standard C.
>>> However, I just happen to have a suitable replacement function
>>> lying about, whose source follows:

>>
>> Come on, strtok_r is part of POSIX. Do you pretend POSIX is not popular
>> enough.

>
> POSIX is very popular. So is cricket. Neither, however is topical here.
>
> If there were no other place where POSIX were already discussed, one
> would have been created, given its popularity.
>
> POSIX is discussed on comp.unix.programmer, and the people there are
> very knowledgeable about the subject.
>


POSIX may not be topical here, but mentioning strtok_r as a widely available
_fixed_ version of broken strtok is more helpful to the OP than the useless
display of obtuse chauvinism expressed ad nauseam by some of the group's
regulars.

Why did C99 get published without including the reentrant alternatives to
strtok and similar functions is a mystery. I guess the national bodies were
too busy arguing about iso646.h. Other Posix utility functions are missing
for no reason: strdup for instance. Did the Posix guys patent those or is
WG14 allergic to unix ?

--
Chqrlie.


 
Reply With Quote
 
Sam Harris
Guest
Posts: n/a
 
      09-15-2007
On 15 Sep 2007 at 1:28, Charlie Gordon wrote:
> Why did C99 get published without including the reentrant alternatives to
> strtok and similar functions is a mystery. I guess the national bodies were
> too busy arguing about iso646.h. Other Posix utility functions are missing
> for no reason: strdup for instance. Did the Posix guys patent those or is
> WG14 allergic to unix ?


You can easily write your own version of strdup in a couple lines. I use
the following:

char *strdup(char *s)
{
char *r=0;
int i=0;
do {
r=(char *) realloc(r,++i * sizeof(char));
} while(r[i-1]=s[i-1]);
return r;
}

 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
strtok_r and delimiters Marco Trapanese C Programming 4 05-20-2008 07:55 PM
strtok and strtok_r siddhu C++ 6 09-15-2007 09:21 AM
what's wrong with this strtok_r() g C++ 4 10-30-2006 11:47 PM
strtok() and std::string Alex Vinokur C++ 6 04-14-2005 01:40 PM
strtok/strtok_r woes kbhat@kaxy.com C Programming 23 01-28-2005 08:55 PM



Advertisments