0

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:

  1. ,arg1, arg2, arg3
  2. arg1, arg2, arg3,
  3. 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

CforLinux
  • 267
  • 2
  • 14
  • The standard functions don't support what you need. – Cheatah Mar 13 '22 at 12:49
  • Consider the non-standard `strsep()` if available, otherwise make your own parser. Or, if there is always also a separating space as apparently shown, use that as the delimiter string and detect the commas in the extracted tokens. – Weather Vane Mar 13 '22 at 12:57
  • The man page for strsep says "The strsep() function was introduced as a replacement for strtok(), since the latter cannot handle empty fields. However, strtok() conforms to C89/C99 and hence is more portable." So it looks like that does exactly what you want as long as the standard library contains the function. This may help: https://stackoverflow.com/questions/7218625/what-are-the-differences-between-strtok-and-strsep-in-c – Jerry Jeremiah Mar 28 '22 at 21:16
  • If you want to make your own have a look at the answer to https://stackoverflow.com/questions/58244300/getting-the-error-undefined-reference-to-strsep-with-clang-and-mingw – Jerry Jeremiah Mar 28 '22 at 21:19

0 Answers0