Simple password-prompt in C

1.4k Views Asked by At

I'm trying to make a simple user and password autentication in C. I was told to never use gets() when getting input and I should use fgets() instead. But I'm not sure of how the fgets() works or why is giving me this input. Here is the code.

#include <stdio.h>
#include <string.h>

int login(char *user, char *passwd){

    int enter = 0;
    char p[6];
    char u[6];
    printf("User: ");
    fgets(u, sizeof u, stdin);
    printf("Pass: "); 
    fgets(p, sizeof p, stdin);
    printf("%s\n", p);
    if (strcmp(user, u) == 0 && strcmp(passwd, p) == 0){
        enter = 1;
    }
    return entrar;
}

int main(){
    char user[] = "admin";
    char passwd[] = "12345";
    if (login(user, passwd)){
        puts("--ACCESS GRANTED--");
    }
    else{
        puts("--Wrong pass or user--");
    }
    return 0;
}

Ouput

User: admin

Pass:

--Wrong pass or user--

It doesn't even let me enter the password after I press enter.

2

There are 2 best solutions below

0
On

well.. you had two problems one as suggested here, you should change the size of u and p to 10, the other is, the fgets also fetches the new line \n that you need to remove before comparing the strings.

so the complete answer would be:

#include <stdio.h>
#include <string.h>

int login(char *user, char *passwd){

    int enter = 0;
    char p[10];
    char u[10];
    char *pos;
    printf("User: ");
    fgets(u, sizeof u, stdin);
    if ((pos=strchr(u, '\n')) != NULL) {
        *pos = '\0';
    }
    printf("'%s'\n", u);
    printf("Pass: "); 
    fgets(p, sizeof p, stdin);
    if ((pos=strchr(p, '\n')) != NULL) {
        *pos = '\0';
    }
    printf("'%s'\n", p);
    if (strcmp(user, u) == 0 && strcmp(passwd, p) == 0){
        enter = 1;
    }
    return enter;
}

int main(){
    char user[] = "admin";
    char passwd[] = "12345";
    if (login(user, passwd)){
        puts("--ACCESS GRANTED--");
    }
    else{
        puts("--Wrong pass or user--");
    }
    return 0;
}
0
On

The problem here is the size of your char[], if you set it to 6, 'admin' will overflow, as reading with gets will read some extra characters.

Try with a bigger string, I'm sure you can afford it, say:

char u[10];
char p[10];

And that is still a quite stingy ;)