views:

149

answers:

3

Hey Folks,

strcmp, when fed the results of strtok, in the following code seems to be blatantly lying to me.

int fSize;
char * buffer=NULL;
char * jobToken = "job";
char * nextToken=NULL;
job * curJob=NULL;
struct node * head=NULL;
struct node * parseList(FILE* file){
    fseek(file,0,SEEK_END);
    fSize=ftell(file);
    buffer = (char*)malloc(fSize+1);
    printf("%d chars: reading buffer now:\n",fSize);
    fseek(file,0,SEEK_SET);
    fread (buffer,1,fSize,file);
    nextToken = strtok(buffer, " \n");
    while (nextToken!=NULL){
            printf("**Running  Token: %s**\n",nextToken);
            if (strcmp(nextToken,jobToken)){
                    printf("Accepted %s  as %s\n",nextToken,jobToken);                
            }else{
                    printf("not %s, %s\n",jobToken,nextToken);
            }

            printf("End of state - %s\n",nextToken);

            nextToken = strtok(NULL, " \n");
    }
    free (buffer);
    return NULL;
}

With this input in a file in the parseList parameters:

job 23
job 10

Gives this output:

14 chars: reading buffer now:
**Running  Token: job**
not job, job
End of state - job
**Running  Token: 23**
Accepted 23  as job
End of state - 23
**Running  Token: job**
not job, job
End of state - job
**Running  Token: 10**
Accepted 10  as job
End of state - 10

LIES!

+6  A: 

strcmp returns 0 when the strings you are comparing are equal. You need to use if (!strcmp(...)).

Dan Moulding
Raaaage! Thanks, seems obvious now.
MJewkes
I prefer to explicitly compare against 0; it reduces the chances of interpreting the result as a Boolean value. I do the same thing with `access`, and pretty much anything else for which zero means success.
Rob Kennedy
+1  A: 

strcmp returns 0 when the strings are equal. See: http://www.elook.org/programming/c/strcmp.html

Richard
+1  A: 

Not related to your question, but a couple of points:

  • After the fread(), you should set buffer[fSize] = 0;, otherwise it's not a string.
  • Determining the numbers of characters to read in either a text file or a binary file using fseek(file,0,SEEK_END); isn't guaranteed to work.

Personally, I would write the malloc() call as:

buffer = malloc(fSize+1);

because that will warn me if I forgot to #include <stdlib.h>, and is easier to read. The cast is not required in C.

Alok