Matthew
Matthew

Reputation: 4607

C - fgets and length of stdin

I have written a program in C which lets the user enter a password to let him into the system or not. I am using the method fgets. The correct password is "letmein". This is the code:

Now I want to verify that the password entered by the user through stdin is no longer than 8 characters. As the program is (without the empty if statement), the user is granted access even if he entered "letmein0000000" since only the first seven characters are fetched by fgets. Now I only want to grant access to the user if he enters "letmein". How can this be done please?

P.S. I have to use fgets since it is a requirement in my project.

Upvotes: 0

Views: 8407

Answers (1)

hmjd
hmjd

Reputation: 121971

From documentation for fgets():

Reads at most count - 1 characters from the given file stream and stores them in str. The produced character string is always NULL-terminated. Parsing stops if end-of-file occurs or a newline character is found, in which case str will contain that newline character.

Request to read a maximum of 8 characters (this means passing 9 as second argument). If the user enters more than 7 characters then it can be caught. Inform user of failure and skip whatever remains in stdin. If the user correctly enters 7 and hits return fgets() will stop at the new-line character.

Check return value of fgets() to ensure the code does not attempt to process an unitialised buffer.

For example:

char password[9];

if (fgets(password, 9, stdin))
{
    /* Strip new-line if present. */
    char* nl = strchr(password, '\n');
    if (nl) *nl = 0;

    if (strlen(password) > 7)
    {
        /* Password too long. 
           Skip remaining input if necessary. */
        int c;
        while ((c = fgetc(stdin)) != EOF && c != '\n');
    }
    else if (0 == strcmp("letmein", password))
    {
        /* Good password. */
    }
    else
    {
        /* Incorrect password. */
    }
}

Upvotes: 6

Related Questions