tags:

views:

49

answers:

2

I want to compare user given input i.e a username to the already stored usernames in /etc/passwd file in ubuntu. I am trying it in C. any help please

A: 

This code prints all the usernames from /etc/passwd.

#include <stdio.h>

int main()
{  
        char buffer[128];
        char* username;
        FILE* passwdFile;

        passwdFile = fopen("/etc/passwd", "r");
        while (fgets(buffer, 128, passwdFile) != NULL)
        {
                username = strtok(buffer, ":");
                printf("username: %s\n", username);
        }
        fclose(passwdFile);
        return 0;
}

Modify to compare username to your input.

Starkey
Much better to use the getpwnam() function that is designed to find the given user name in the password database, which might not always be (just) the /etc/passwd file.
Jonathan Leffler
+4  A: 
#include <pwd.h>
...

struct passwd *e = getpwnam(userName);
if(e == NULL) {
   //user not found
} else {
  //found the user
}

See docs here and here

(If you actually want to authenticate the user as well, there's more work needed though )

nos