Search code examples
cgetlinestrncmp

strncmp() gives a false positive


I have been expirencing an issue with strncmp and getline... so a i made a little test app. strncmp gives false positives and i can't figure out what i am doing wrong.

this is the program

#include <stdio.h>

FILE *fp=NULL;
char uname[4]="test";
char *confline=NULL;
size_t conflinelength=0;
int datlength;

main()
{
    datlength=4;
    fp=fopen("test.txt","r+");
    while (getline(&confline,&conflinelength,fp)!=-1)
    {
        if (strncmp(confline,uname,(datlength-1))==0);
        {
            printf("match\n");
            return;
        }
    }
    printf("no match\n");
    fclose(fp);
}

and this is "test.txt"...

bjklas

and the program outputs

match

Solution

  • if (strncmp(confline,uname,(datlength-1))==0);
        printf("match\n");
    

    is equivalent to

    if (strncmp(confline,uname,(datlength-1))==0)
        ;
    printf("match\n");
    

    You need to remove the ; from the end of your if line