C - strcmp does not return 0 for equal lines

So, I tried to find a solution for this, but I can really find messages in which a new line or zero byte is missing from one of the lines. I am absolutely sure that this is not so.

I use the following function to compare a word with a file containing a list of words with one word on each line (a dictionary in a function). Here is the code:

int isWord(char * word,char * dictionary){ FILE *fp; fp = fopen(dictionary,"r"); if(fp == NULL){ printf("error: dictionary cannot be opened\n"); return 0; } if(strlen(word)>17){ printf("error: word cannot be >16 characters\n"); return 0; } char longWord[18]; strcpy(longWord,word); strcat(longWord,"\n"); char readValue[50] = "a\n"; while (fgets(readValue,50,fp) != NULL && strcmp(readValue,longWord) != 0){ printf("r:%sw:%s%d\n",readValue,longWord,strcmp(longWord,readValue));//this line is in for debugging } if(strcmp(readValue,longWord) == 0){ return 1; } else{ return 0; } } 

The code compiles without errors, and the function perfectly reads the dictionary file and prints a list of words as they appear. The problem I am facing is that even when the two lines are identical, strcmp does not return 0, so the function returns false for any input.

for example, I get:

 r:zymoscope w:zymoscope -3 

Any ideas? I feel like I should be missing out on something obvious, but I could not find anything in my quest.

+5
source share
2 answers

I see that you are adding newline to your test lines in order to try to solve the fgets() problem while keeping the line endings. It is much better to fix this at the source. You can split all trailing files like this right after reading from the file.

 readValue [ strcspn(readValue, "\r\n") ] = '\0'; // remove trailing newline etc 
+5
source

The line you are reading contains the terminating character (s) and therefore does not match the line you are comparing.

Delete the trailing newline (and CR, if any); then you don’t need to add a new line or carriage return to the line being compared:

 int isWord(char *word, char *dictionary){ FILE *fp; fp = fopen(dictionary, "r"); if (fp == NULL){ fprintf(stderr, "error: dictionary cannot be opened\n"); return 0; } if (strlen(word) > 16){ fprintf(stderr, "error: word cannot be >16 characters\n"); return 0; } char readValue[50]; while (fgets(readValue, 50, fp) != NULL){ char *ep = &readValue[strlen(readValue)-1]; while (*ep == '\n' || *ep == '\r'){ *ep-- = '\0'; } if (strcmp(readValue, word) == 0){ return 1; } } return 0; } 
+4
source

All Articles