0

Okay, this is just part of a simple client-server program. Right now I'm just trying to implement a simple login checker.

Inside the Users.txt file is just one line: "Bryan". So far I cannot get strncmp to produce a positive response.

#include <stdio.h>
#include <string.h>
#define BUFSIZE 1024

int main()
{
FILE * userf;

userf = fopen("Users.txt", "r");
char usrstr[30];

char buffer[30];    
char userbuffer[30];

fgets (buffer, sizeof(buffer), userf); //loads Users.txt in buffer

gets(userbuffer); //type whatever user
printf ("Your login is: %s\n", userbuffer);

if(strncmp (buffer, userbuffer, sizeof(userbuffer)) == 0)
{ 
 sprintf(usrstr, "\nCorrect login received.\n"); // faster than printf
 puts(usrstr); //displays content of sprintf above
 bzero(usrstr, sizeof(usrstr)); //clears usrstr buffer

 printf("buffer is %s.\n",buffer); //for checking
 printf("userbuffer is %s.\n",userbuffer); //for checking
}

else
{
 sprintf(usrstr, "\nIncorrect login received.\n");
 puts(usrstr);
 bzero(usrstr, sizeof(usrstr));

 printf("buffer is %s.\n",buffer); //for checking
 printf("userbuffer is %s.\n",userbuffer); //for checking
}   

fclose(userf);
return(0);
}

And then for the output I get:

Bryan
Your login is: Bryan

Incorrect login received.

buffer is Bryan
.
userbuffer is Bryan.

I'm guessing the long spacing after the buffer is the key cause, but I have no idea as to what is causing it. My programming skills are pretty crap, so any assistance would be greatly appreciated.

gwar666
  • 13
  • 1
  • 4
  • Side note: 1. Open `stdio.h`. 2. Find the prototype for `gets()` 3. delete that line of code. 4. Save the file. That function is *Evil* with a capital E. Don't use it. – WhozCraig Aug 25 '13 at 18:49

2 Answers2

0

Well it works for me

You've a newline [ENTER] in your Users.Txt after "Bryan"

Remove the newline from the text file.

Or

Use

fgets (buffer,strlen(userbuffer)+1, userf);

after the user input

P0W
  • 46,614
  • 9
  • 72
  • 119
  • Hm, weird. opening the Users.txt in Ubuntu (running it in a VM) using gedit had no newlines, but copying it to my Win7 desktop and running Notepad revealed that it indeed had a newline. At any rate, my problem is solved, thanks :) – gwar666 Aug 25 '13 at 18:25
0

try changing

if(strncmp (buffer, userbuffer, sizeof(userbuffer)) == 0)

to

if(strncmp (buffer, userbuffer, strlen(userbuffer)) == 0)

That way it'll only be comparing for the length of thr string - not the entire buffer

mp3ferret
  • 1,183
  • 11
  • 16