Get the first element of the first element of an string in C

685 views Asked by At

I have a variable in which I read a .txt file. The file looks like this:

Element1|Element2|Element3|...|ElementLast#Element1|Element2|Element3|...|ElementLast#Element1|Element2|Element3|...|ElementLast#Element1|Element2|Element3|...|ElementLast


Now what I wanna do is, to get every 'Element1' and check if it is equal to an specific string.
I read much about the function strtok() and I tried to use it.
This is my function: (id is this special string, I convert it during the function.)

int PLUexists(int id) {

    char idc[3];
    sprintf(idc, "%d", id);
    printf("%s", idc);

    /* My Main String */
    FILE *plu = fopen("kassa_plu.txt", "r");
    char pluc[2000];
    while( fgets(pluc, sizeof(pluc), plu) !=0 );

    /* My Token */
    char *token;

    /* get first line */
    token = strtok(pluc, "#");

    while( token != NULL ) {
        printf(" %s \n", token);

        // Without that block, I get all lines seperated...
        char t[255];
        strcpy(t, token);

        if ( strcmp(strtok(t, "|"), idc) == 0) {
            printf("Jep");
            return 1;
        }
        // End 'block'

        token = strtok(NULL, "#");
    }
    return 0;
}

Now if I just print out the first token (and repeat it), I get all of my lines seperated (see underneath) but when I also parse the code between the printf(" %s \n", token); and token = strtok(NULL, "#"); it won't work.

Without the block:

Element1|Element2|Element3|...|ElementLast
Element1|Element2|Element3|...|ElementLast
Element1|Element2|Element3|...|ElementLast
Element1|Element2|Element3|...|ElementLast

With it:

Element1|Element2|Element3|...|ElementLast
Element2|Element3|...|ElementLast
Element3|...|ElementLast
...|ElementLast
ElementLast
1

There are 1 answers

0
John Bollinger On BEST ANSWER

Your main problem is that when, inside the loop, you call strtok() with a non-null first argument, you thereby tell that function to abandon the previous tokenization (by # delimiters) it was working on to perform a new tokenization. You could consider using strtok_r() instead, which allows you to maintain state for multiple tokenizations at once, but since you want the first token on each line and only the first, I'd consider not using strtok[_r]() in the inner loop at all.

For example, here's a similar approach based on strchr():

    while( token != NULL ) {
        printf(" %s \n", token);

        char *delim = strchr(token, '|');
        if (delim) *delim = '\0';

        if (strcmp(token, idc) == 0) {
            printf("Jep");
            return 1;
        }

        token = strtok(NULL, "#");
    }