Sujet : Re: Command line globber/tokenizer library for C?
De : tr.17687 (at) *nospam* z991.linuxsc.com (Tim Rentsch)
Groupes : comp.lang.cDate : 13. Sep 2024, 17:05:04
Autres entêtes
Organisation : A noiseless patient Spider
Message-ID : <861q1nfsjz.fsf@linuxsc.com>
References : 1 2 3 4 5 6 7 8 9 10 11 12 13
User-Agent : Gnus/5.11 (Gnus v5.11) Emacs/22.4 (gnu/linux)
Michael S <
already5chosen@yahoo.com> writes:
[..iterate over words in a string..]
#include <stddef.h>
>
void parse(const char* src,
void (*OnToken)(const char* beg, size_t len, void* context),
void* context) {
char c0 = ' ', c1 = '\t';
const char* beg = 0;
for (;;src++) {
char c = *src;
if (c == c0 || c == c1 || c == 0) {
if (beg) {
OnToken(beg, src-beg, context);
c0 = ' ', c1 = '\t';
beg = 0;
}
if (c == 0)
break;
} else if (!beg) {
beg = src;
if (c == '"') {
c0 = c1 = c;
++beg;
}
}
}
}
I couldn't resist writing some code along similar lines. The
entry point is words_do(), which returns one on success and
zero if the end of string is reached inside double quotes.
typedef struct gopher_s *Gopher;
struct gopher_s { void (*f)( Gopher, const char *, const char * ); };
static _Bool collect_word( const char *, const char *, _Bool, Gopher );
static _Bool is_space( char );
_Bool
words_do( const char *s, Gopher go ){
char c = *s;
return
is_space(c) ? words_do( s+1, go ) :
c ? collect_word( s, s, 1, go ) :
/***************/ 1;
}
_Bool
collect_word( const char *s, const char *r, _Bool w, Gopher go ){
char c = *s;
return
c == 0 ? go->f( go, r, s ), w :
is_space(c) && w ? go->f( go, r, s ), words_do( s, go ) :
/***************/ collect_word( s+1, r, w ^ c == '"', go );
}
_Bool
is_space( char c ){
return c == ' ' || c == '\t';
}