-1

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

rahul
  • 1
  • If you've made an attempt, can you post what you have so far? It's not really clear what your goal is. – Bob Aug 26 '10 at 16:16
  • i want to write a program to validate user in ubuntu ....input is user given and it is compared to /etc/passwd file – rahul Aug 26 '10 at 16:22
  • 2
    possible duplicate of http://stackoverflow.com/questions/3567809/how-to-read-a-linux-etc-passwd-file-and-compare-the-user-input-name-for-authentic – torak Aug 26 '10 at 16:23
  • is this an assignment? seen the coincidence that the same question was asked yesterday do you follow the same course? – Jens Gustedt Aug 26 '10 at 17:41

2 Answers2

4
#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
  • 223,662
  • 58
  • 417
  • 506
0

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
  • 9,673
  • 6
  • 31
  • 51
  • 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 Aug 27 '10 at 02:10