xref: /netbsd-src/external/ibm-public/postfix/dist/src/util/mystrtok.c (revision a5847cc334d9a7029f6352b847e9e8d71a0f9e0c)
1 /*	$NetBSD: mystrtok.c,v 1.1.1.1 2009/06/23 10:09:00 tron Exp $	*/
2 
3 /*++
4 /* NAME
5 /*	mystrtok 3
6 /* SUMMARY
7 /*	safe tokenizer
8 /* SYNOPSIS
9 /*	#include <stringops.h>
10 /*
11 /*	char	*mystrtok(bufp, delimiters)
12 /*	char	**bufp;
13 /*	const char *delimiters;
14 /* DESCRIPTION
15 /*	mystrtok() splits a buffer on the specified \fIdelimiters\fR.
16 /*	Tokens are delimited by runs of delimiters, so this routine
17 /*	cannot return zero-length tokens.
18 /*
19 /*	The \fIbufp\fR argument specifies the start of the search; it
20 /*	is updated with each call. The input is destroyed.
21 /*
22 /*	The result value is the next token, or a null pointer when the
23 /*	end of the buffer was reached.
24 /* LICENSE
25 /* .ad
26 /* .fi
27 /*	The Secure Mailer license must be distributed with this software.
28 /* AUTHOR(S)
29 /*	Wietse Venema
30 /*	IBM T.J. Watson Research
31 /*	P.O. Box 704
32 /*	Yorktown Heights, NY 10598, USA
33 /*--*/
34 
35 /* System library. */
36 
37 #include "sys_defs.h"
38 #include <string.h>
39 
40 /* Utility library. */
41 
42 #include "stringops.h"
43 
44 /* mystrtok - safe tokenizer */
45 
46 char   *mystrtok(char **src, const char *sep)
47 {
48     char   *start = *src;
49     char   *end;
50 
51     /*
52      * Skip over leading delimiters.
53      */
54     start += strspn(start, sep);
55     if (*start == 0) {
56 	*src = start;
57 	return (0);
58     }
59 
60     /*
61      * Separate off one token.
62      */
63     end = start + strcspn(start, sep);
64     if (*end != 0)
65 	*end++ = 0;
66     *src = end;
67     return (start);
68 }
69 
70 #ifdef TEST
71 
72  /*
73   * Test program: read lines from stdin, split on whitespace.
74   */
75 #include "vstring.h"
76 #include "vstream.h"
77 #include "vstring_vstream.h"
78 
79 int     main(void)
80 {
81     VSTRING *vp = vstring_alloc(100);
82     char   *start;
83     char   *str;
84 
85     while (vstring_fgets(vp, VSTREAM_IN)) {
86 	start = vstring_str(vp);
87 	while ((str = mystrtok(&start, " \t\r\n")) != 0)
88 	    vstream_printf(">%s<\n", str);
89 	vstream_fflush(VSTREAM_OUT);
90     }
91     vstring_free(vp);
92     return (0);
93 }
94 
95 #endif
96