1 /***************************************************************************
2 utils.cpp - sytem dependent utilities
4 begin : lun ott 24 2005
5 copyright : (C) 2005-2007 by Maurizio Monge
6 email : monge@linuz.sns.it
7 ***************************************************************************/
9 /***************************************************************************
11 * This program is free software; you can redistribute it and/or modify *
12 * it under the terms of the GNU General Public License as published by *
13 * the Free Software Foundation; either version 2 of the License, or *
14 * (at your option) any later version. *
16 ***************************************************************************/
22 char **get_tokenized(int* numtokens
, bool accept_quotes
)
24 return fget_tokenized(stdin
, numtokens
, accept_quotes
);
27 char **get_tokenized(const char *whitespaces
, int* numtokens
, bool accept_quotes
)
29 return fget_tokenized(stdin
, whitespaces
, numtokens
, accept_quotes
);
32 char **fget_tokenized(FILE* f
, int* numtokens
, bool accept_quotes
)
34 return fget_tokenized(f
, " \v\t\r\n", numtokens
, accept_quotes
);
37 char **fget_tokenized(FILE* f
, const char *whitespaces
, int* numtokens
, bool accept_quotes
)
40 if(!fgets(str
, 4096, f
))
42 return tokenize(str
, whitespaces
, numtokens
, accept_quotes
);
45 char **tokenize(const char *str
, int* numtokens
, bool accept_quotes
)
47 return tokenize(str
, " \v\t\r\n", numtokens
, accept_quotes
);
50 char **tokenize(const char *str
, const char *whitespaces
, int* numtokens
, bool accept_quotes
)
52 int len
= strlen(str
);
53 const char *ptr
= str
;
58 ptr
+= strspn(ptr
, whitespaces
);
59 int s
= strcspn(ptr
, whitespaces
);
67 //printf("ntoks = %d\n", ntoks);
69 void* block
= malloc((ntoks
+1)*sizeof(char*) + len
+1);
70 char** retv
= (char**)block
;
71 char* buf
= (char*)block
+ (ntoks
+1)*sizeof(char*);
78 ptr
+= strspn(ptr
, whitespaces
);
79 //printf("-> \"%s\"\n", ptr);
85 while( *ptr
&& (quoted
|| (strchr(whitespaces
, *ptr
) == NULL
) ) )
87 if(accept_quotes
&& *ptr
== '"')
94 if(quoted
&& *ptr
== '\\')
122 printf("Error! Missing terminating '\"' while parsing!\n");
130 retv
[ntoks
++] = NULL
;