I'm using strtok in order to parse an argument list where every argument is separated by a comma, e.g arg1, arg2, arg3 and I need to check for these 3 erros in the format:
,arg1, arg2, arg3arg1, arg2, arg3,arg1,, arg2, arg3
for the first case strtok digest the first comma, and return the first arg, in the second case strtok return NULL as it finished digesting the string, and the third case is similar to the first strtok just digest the consecutive commas. Is there a way in C to detect those errors apart from writing a new function for breaking the string?
I tried to make my version of strtok to check for this
int my_strtok(char * str, char delim, char ** token) {
int res = 0;
static char * next;
char * ptr;
if (NULL != str) {
next = str;
}
ptr = next;
while (delim != *next && 0 != *next) {
next++;
}
if (delim == *next) {
*next = 0;
next++;
}
if (1 == next - ptr) {
res = -1; /* error */
}
if (0 == *ptr) {
*token = NULL;
} else {
*token = ptr;
}
return res;
}
But I would rather have something standard.
PS I need something conforming to ANSI C