0

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
MrBlarg64
  • 13
  • 1
  • 2

4 Answers4

4
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

simonc
  • 41,632
  • 12
  • 85
  • 103
3
if (strncmp(confline,uname,(datlength-1))==0);
                                             ^ roh-roh
Charlie Burns
  • 6,994
  • 20
  • 29
0

If you would have usedchar uname[5]="test"; this line would have automatically appended the '\0', making it a C string, but with only 4 spaces allocated, it couldn't. Instead, it is an unterminated char array...

char uname[4]="test"; results in an unterminated set of chars, i.e. not a C string. i.e. "|t|e|s|t|"
This will compile, but it cannot be processed by some string functions, (strcmp, strlen,etc) resulting in run-time errors.

Suggest char uname[]="test"; this will automatically take care of appending the NULL terminator yielding a C string: "|t|e|s|t|\0|". This method is a preferred way to initialize char arrays.

ryyker
  • 22,849
  • 3
  • 43
  • 87
0

I guess it is your typo when you put the semicolon ; at the end of if condition instead of its statement, i.e. right after the curve bracket }

Out of interest, I would prefer using fgets because getline is not in a standard C library

Tu Bui
  • 1,660
  • 5
  • 26
  • 39