473,796 Members | 2,703 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

strtok and strtok_r

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

Sep 14 '07 #1
75 25143
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;
}
Sep 14 '07 #2
siddhu <si***********@ gmail.comwrites :
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.
[...misunderstan ding...]
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);in t main(void){unsi gned long b[]
={0x67dffdff,0x 9aa9aa6a,0xa77f fda9,0x7da6aa6a ,0xa67f6aaa,0xa a9aa9f6,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)bre ak;else default:continu e;if(0)case 1:putchar(a[i&15]);break;}}}
Sep 14 '07 #3
"siddhu" <si***********@ gmail.coma écrit dans le message de news:
11************* *********@g4g20 00...legro ups.com...
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.
Sep 14 '07 #4
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

Sep 14 '07 #5
"CBFalconer " <cb********@yah oo.coma écrit dans le message de news:
46************* **@yahoo.com...
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.
Sep 14 '07 #6
On Sat, 15 Sep 2007 01:07:48 +0200,
Charlie Gordon <ne**@chqrlie.o rgwrote:
"CBFalconer " <cb********@yah oo.coma écrit dans le message de news:
46************* **@yahoo.com...
>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.progr ammer, 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.
|
Sep 15 '07 #7
"Martien verbruggen" <mg**@tradingpo st.com.aua écrit dans le message de
news: sl************* ****@martien.he liotrope.home...
On Sat, 15 Sep 2007 01:07:48 +0200,
Charlie Gordon <ne**@chqrlie.o rgwrote:
>"CBFalconer " <cb********@yah oo.coma écrit dans le message de news:
46************* **@yahoo.com...
>>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.progr ammer, 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.
Sep 15 '07 #8
Charlie Gordon wrote:
"CBFalconer " <cb********@yah oo.coma é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

Sep 15 '07 #9
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;
}

Sep 15 '07 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

23
3780
by: kbhat | last post by:
I had written some code using strtok_r for parsing strings with two "levels" of delimiters. The code was working like a charm, until it suddenly broke one day. You see, I was applying strtok on the input string itself, and as long as a variable string was passed to the function, everything was hunky dory. Then one day somebody decided to pass a constant string to my code ---- and everything came collapsing down like a domino. I...
6
476
by: gyan | last post by:
Hi How strtok track through string? char *strtok(char *s1, const char *s2); As i know The first call (with pointer s1 specified) returns a pointer to the first character of the first token, and will have written a null character into s1 immediately following the returned token. The function keeps track of its position in the string between separate calls, so that subsequent calls (which must be made with the first argument...
13
4927
by: ern | last post by:
I'm using strtok( ) to capture lines of input. After I call "splitCommand", I call strtok( ) again to get the next line. Strtok( ) returns NULL (but there is more in the file...). That didn't happen before 'splitCommands' entered the picture. The problem is in splitCommands( ) somehow modifying the pointer, but I HAVE to call that function. Is there a way to make a copy of it or something ? /* HERE IS MY CODE */ char *...
33
1022
by: Geometer | last post by:
Hello, and good whatever daytime is at your place.. please can somebody tell me, what the standard behavior of strtok shall be, if it encounters two or more consecutive delimiters like in (checks omitted) char tst = "this\nis\n\nan\nempty\n\n\nline"; ^^^^ ^^^^^^ char *tok = strtok(tst, "\n");
18
3498
by: Robbie Hatley | last post by:
A couple of days ago I dedecided to force myself to really learn exactly what "strtok" does, and how to use it. I figured I'd just look it up in some book and that would be that. I figured wrong! Firstly, Bjarne Stroustrup's "The C++ Programming Language" said: (nothing)
4
2736
by: Michael | last post by:
Hi, I have a proble I don't understand when using strtok(). It seems that if I make a call to strtok(), then make a call to another function that also makes use of strtok(), the original call is somehow confused or upset. I have the following code, which I am using to tokenise some input which is in th form x:y:1.2: int tokenize_input(Sale *sale, char *string){
14
3326
by: Mr John FO Evans | last post by:
I cam across an interesting limitation to the use of strtok. I have two strings on which I want strtok to operate. However since strtok has only one memory of the residual string I must complete one set of operations before starting on the second. This is inconvenient in the context of my program! So far the only solution I can see is to write a replacement for strtok to use on one of the strings. Can anyone offer an alternative?
3
441
by: siddhu | last post by:
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-...
11
17179
by: magicman | last post by:
can anyone point me out to its implementation in C before I roll my own. thx
0
9685
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9533
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10461
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10239
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10190
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
1
7555
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6796
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5579
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3736
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.