Page 1 of 1

C - homebrew strtok

Posted: Sun May 03, 2009 11:18 pm
by M_D_K
So this code came into existence cause avansc wanted to see how I'd do it and so he could use it. Clearly neither of us knew about strtok.

Code: Select all

char *nextToken(char* data, char delimiter)
{
    char *pos = strchr(data, (int)delimiter);
    if(pos == NULL)
    {
        return NULL;
    }

    char *ret = (char *)malloc((pos-data+1)*sizeof(char));
    strncpy(ret, data,(pos-data));
    
    //just in case read and write addresses overlap (it shouldn't)
    strcpy(data, pos+1);//here so strncpy doesn't fuck up

    return ret;
};
EDIT: So it turns out avansc likes this code more than strtok :mrgreen:
EDIT2: Ginto made it segfault(no surprise there) so added a little something to remove user(coder) stupidity.

Re: C - homebrew strtok

Posted: Mon May 04, 2009 3:08 pm
by MarauderIIC
M_D_K wrote:So this code came into existence cause avansc wanted to see how I'd do it and so he could use it. Clearly neither of us knew about strtok.
Noobs. :)

Re: C - homebrew strtok

Posted: Tue May 05, 2009 11:31 am
by sparda
Include me in the Noob bunch; I had no idea about strtok() :shock2:

Re: C - homebrew strtok

Posted: Tue May 05, 2009 12:08 pm
by avansc
he neglects to mention that i said. wait. there is this..... strtok.............................................................fux

Re: C - homebrew strtok

Posted: Tue May 05, 2009 7:56 pm
by MarauderIIC
He mentioned that you had difficulty using it. Check the manual, it's sort of strange (NULL calls after first). The way it's handled also means you can't tokenize two strings in parallel with strtok.