Long spacing after loading buffer from text file

60 Views Asked by At

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.

2

There are 2 best solutions below

1
On BEST ANSWER

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

0
On

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