Chen Yao
Chen Yao

Reputation: 19

Getting parameters through tokens in a char array

I have a text file with a output similar to this style:

some text 10 trials other text here 12 trials and a bit more txt 20 trials

some text here 7 trials text 16 trials and more txt 20 trials

etc

What I'm trying to do is getting the values before trials I have a code that work theoretically but breaks because the text is manipulated isn't the same as when you run strcmp()

char *fileToString(char *fileName){
    FILE *file = fopen(fileName, "rb");
    long lSize;

    fseek(file, 0, SEEK_END);
    lSize = ftell(file);
    fseek(file, 0, SEEK_SET);

    char *buffer = malloc(lSize);
    fread(buffer, 1, lSize, file);
    fclose(file);
    return buffer;
}

The main looks something like this.

    path[20] = "path/to/file.txt";
    char *a = fileToString(path);
    char trial[6] = "trials";
    char *token, *tmp;
    token = strtok(a, " \n");
    tmp = token;
    while(token != NULL){
        if(strcmp(token, trial)==0){
            printf("%s trials\n", tmp);
        }
        printf("tmp: %s | token %s | strcmp %d\n", tmp, token, strcmp(token,trial));
        tmp = token;
        token = strtok(NULL, " \n");
        
    }

The result should be

10 trials
12 trials
20 trials
7 trials
16 trials
20 trials

etc but the strcmp(token, trial) sometimes gives me non-zero even when the token and trial should be matching. When I printed the strcmp() values this is what I got in the result

tmp: 12 | token trials | strcmp -81
...

Upvotes: 0

Views: 31

Answers (1)

VolAnd
VolAnd

Reputation: 6407

Pay attention at

 char trial[6] = "trials";

Here trial[6] should be trial[7] to store not only letters, but also '\0' (end of line)

Upvotes: 3

Related Questions