Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

strtok_r for MinGW

Tags:

c

mingw

strtok

strtok_r is the reentrant variant of strtok. It is POSIX-conformant. However, it is missing from MinGW, and I'm trying to compile a program that is using it.

Is there any way I could add a standard implementation of this function, perhaps to the project's own code, or to MinGW's standard library functions?

like image 502
sashoalm Avatar asked Oct 19 '12 13:10

sashoalm


4 Answers

Since there are some license questions about the code from another answer, here's one that's explicitly public domain:

/* 
 * public domain strtok_r() by Charlie Gordon
 *
 *   from comp.lang.c  9/14/2007
 *
 *      http://groups.google.com/group/comp.lang.c/msg/2ab1ecbb86646684
 *
 *     (Declaration that it's public domain):
 *      http://groups.google.com/group/comp.lang.c/msg/7c7b39328fefab9c
 */

char* strtok_r(
    char *str, 
    const char *delim, 
    char **nextp)
{
    char *ret;

    if (str == NULL)
    {
        str = *nextp;
    }

    str += strspn(str, delim);

    if (*str == '\0')
    {
        return NULL;
    }

    ret = str;

    str += strcspn(str, delim);

    if (*str)
    {
        *str++ = '\0';
    }

    *nextp = str;

    return ret;
}
like image 162
Michael Burr Avatar answered Nov 15 '22 19:11

Michael Burr


Here's the source code which you can simply add to your own library/function in your project:

char *strtok_r(char *str, const char *delim, char **save)
{
    char *res, *last;

    if( !save )
        return strtok(str, delim);
    if( !str && !(str = *save) )
        return NULL;
    last = str + strlen(str);
    if( (*save = res = strtok(str, delim)) )
    {
        *save += strlen(res);
        if( *save < last )
            (*save)++;
        else
            *save = NULL;
    }
    return res;
}
like image 35
P.P Avatar answered Nov 15 '22 18:11

P.P


Is the FreeBSD implementation any use to you?

Its liberally licensed but integrating it may have some requirements on your project documentation (adding an acknowledgement that the code has been included).

like image 23
simonc Avatar answered Nov 15 '22 18:11

simonc


MINGW has no implementation of strtok_r. However you can find a thread-safe implementation in the link below:

http://www.raspberryginger.com/jbailey/minix/html/strtok__r_8c-source.html

like image 33
Claudix Avatar answered Nov 15 '22 18:11

Claudix